Skip to main content

Robust Error Handling for Didit API in Rust

Master advanced error handling for production-grade Didit API integrations in Rust. Learn about custom error types, retry mechanisms, rate limit management, and the benefits of Didit's resilient API and modular platform for.

Robust Error Handling for Didit API in Rust

Contents

In this guide

Jump to the part you need.

Custom Error Types for ClarityImplementing custom error enums in Rust provides granular control and clear mapping of Didit API responses, enhancing debuggability and maintainability for complex identity verification workflows.

Intelligent Retry and Backoff StrategiesRobust API integrations must incorporate exponential backoff and jitter for transient errors, preventing system overload and ensuring high availability when interacting with external services like Didit's identity platform.

Proactive Rate Limit ManagementIntegrating Didit's API requires careful attention to rate limits, utilizing response headers (X-RateLimit-Remaining, X-RateLimit-Reset) to self-throttle requests and implement dynamic queuing, crucial for seamless operation at scale.

Didit's Resilient and Developer-First DesignDidit's API is built for reliability, offering clear rate limit headers, predictable error responses, and a modular architecture that simplifies integration and allows developers to focus on building robust, secure identity verification systems without hidden complexities.

Integrating external APIs into production systems demands meticulous attention to error handling. For high-stakes operations like identity verification, where reliability and security are paramount, a robust error strategy is not just good practice—it's essential. This blog post delves into advanced error handling techniques specifically for integrating Didit's powerful identity verification API into Rust applications, ensuring your system is resilient, performant, and secure.

Crafting Custom Error Types for Didit API Responses

Rust's strong type system makes it an ideal language for defining precise error types. When integrating with Didit, you'll encounter various error scenarios, from network issues to API-specific validation failures. Instead of relying on generic error messages, creating custom error enums allows you to categorize and react to these issues effectively.

Consider an enum that captures potential failures when calling Didit's API, such as creating a verification session or retrieving a decision:

enum DiditError {
    NetworkError(reqwest::Error),
    ApiError { status: u16, message: String },
    RateLimitExceeded { retry_after_seconds: u64 },
    InvalidInput(String),
    SerializationError(serde_json::Error),
    // ... other specific errors
}

impl From<reqwest::Error> for DiditError {
    fn from(err: reqwest::Error) -> Self {
        DiditError::NetworkError(err)
    }
}

impl From<serde_json::Error> for DiditError {
    fn from(err: serde_json::Error) -> Self {
        DiditError::SerializationError(err)
    }
}

This approach provides clear error propagation and allows your application logic to pattern match on specific error variants, leading to more targeted recovery strategies. For instance, a RateLimitExceeded error would trigger a different response than an InvalidInput error, which might require user intervention. Didit's API provides detailed error messages and HTTP status codes, making it straightforward to map these into your custom error types for services like Didit's ID Verification or AML Screening.

Implementing Intelligent Retry Mechanisms with Exponential Backoff

Transient network issues or temporary service unavailability are inevitable when dealing with external APIs. A robust integration must implement intelligent retry logic. Simple retries can exacerbate problems, so exponential backoff with jitter is crucial.

When Didit's API returns a 5xx server error, or a 429 Too Many Requests error (which we'll cover next), your application should wait for an increasing duration before retrying the request. Jitter (adding a small random delay) prevents a "thundering herd" problem where multiple clients retry simultaneously, overwhelming the service.

async fn call_didit_api_with_retry<F, Fut, T>(
    action: F,
    max_retries: u8,
) -> Result<T, DiditError>
where
    F: Fn() -> Fut,
    Fut: Future<Output = Result<T, DiditError>>,
{
    let mut retries = 0;
    loop {
        match action().await {
            Ok(val) => return Ok(val),
            Err(e @ DiditError::NetworkError(_)) | Err(e @ DiditError::ApiError { status: 500..=599, .. }) => {
                if retries < max_retries {
                    let delay = Duration::from_secs(2u64.pow(retries) + rand::thread_rng().gen_range(0..10));
                    tokio::time::sleep(delay).await;
                    retries += 1;
                } else {
                    return Err(e);
                }
            },
            Err(e) => return Err(e),
        }
    }
}

This pattern ensures that your application remains resilient even when facing temporary hiccups, minimizing service interruptions for critical functions like Didit's Liveness Detection or NFC Verification.

Proactive Rate Limit Management

Didit, like any well-designed API, implements rate limiting to ensure stability and fair usage. Ignoring these limits can lead to 429 Too Many Requests errors and potentially temporary blocking. Didit's API provides informative headers to help you manage your request volume:

  • X-RateLimit-Limit: The maximum number of requests allowed in a window.
  • X-RateLimit-Remaining: The number of requests remaining in the current window.
  • X-RateLimit-Reset: The time (in epoch seconds) when the rate limit window resets.
  • Retry-After: If a 429 is returned, this header indicates how long to wait before retrying.

Your Rust application should monitor these headers, especially X-RateLimit-Remaining. When it drops below a certain threshold (e.g., 15% of the limit), you should proactively slow down or queue requests. If a 429 is received, always respect the Retry-After header for the specified duration before making further requests.

For example, when creating sessions via POST /v3/session/, Didit has a global limit of 300 requests per minute per application for write endpoints, and endpoint-specific limits like 600 rpm for session-v2-create. Proactive management prevents service interruptions for critical identity verification processes, such as initiating Age Estimation or Proof of Address checks.

How Didit Helps

Didit's platform is designed with robustness and developer experience in mind, making error handling significantly simpler. Our AI-native, modular architecture provides clear API responses and standardized error codes that seamlessly integrate with your Rust application's custom error types. The API consistently provides rate limit headers, enabling your system to implement proactive self-throttling and backoff strategies effectively. With Didit's Core KYC and pay-per-use pricing, you can build and test these advanced error handling strategies without upfront costs. Our comprehensive SDKs and clean APIs simplify the integration of powerful features like ID Verification, Passive & Active Liveness, and AML Screening & Monitoring. Didit's focus on structured identity data and orchestrated workflows means fewer unexpected errors and more predictable outcomes, allowing your team to automate trust with confidence.

Ready to Get Started?

Ready to see Didit in action? Get a free demo today.

Start verifying identities for free with Didit's free tier.

Try it

Try this in the sandbox

Run the check this guide describes, free.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alberto Rosas

Co-founder and CEO

Alberto Rosas

Alberto Rosas

Co-founder and CEO

About Didit

Questions

Blog questions

Who writes the Didit blog?
The Didit team. Guides reviewed by Alberto Rosas, co-founder and CEO, carry his byline. The rest are published as Didit.
Which topics does the blog cover?
Eight topics: ID verification, business verification (KYB), AML, sanctions and compliance, fraud prevention, transaction monitoring and crypto, country guides, agents and developers, and product updates.
Is the blog available in my language?
Yes, in 15 languages: English, Spanish, French, German, Brazilian and European Portuguese, Catalan, Russian, Arabic, Chinese, Japanese, Hindi, Indonesian, Korean and Swahili. Not every post is translated, so each language shows the posts it has.
Where do I find product updates?
In the changelog at /changelog/ and under the Product updates topic.
Are these posts legal advice?
No. Regulation posts explain rules; your legal team decides how they apply.
How do I find posts on one topic?
Open one of the eight topics, or search the blog.
Are posts dated?
Yes. Every post shows when it was published and when it was last updated.
Do posts link to the docs?
Developer posts link to the matching page on docs.didit.me and to the API reference.
Is the blog the same as the docs?
No. The blog explains rules, markets and product changes for a general reader, while docs.didit.me holds the integration guides and the API reference. Developer posts link the matching docs page and the API reference they describe.

Compliance built in

Audited, certified and attested.

We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center

  • Regulation encoded into your flows

    Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.

  • Ready for AMLR

    Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.

  • Tested in Spain's Treasury sandbox

    Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.

  • Audited, not self-declared

    iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • SOC 2 Type 2
  • ISO 27001
  • iBeta Level 1 and Level 2
  • EU regulator attestation
  • FSM youth protection
  • GDPR
  • EBA remote onboarding
  • MiCA compatible
  • FIDO Alliance member
  • AMLREU AML Regulation ready

Integration · Didit MCP

Run Didit from your own AI agent

Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
  • Run investigationsAsk why a session was declined, review cases, search people and companies.
  • Change rulesCreate payment rules, test them on past data and switch them on.
  • Pull reportsAsk for numbers, exports or the audit log.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.