Skip to main content

Idempotent API Calls in Go for Identity Verification (2026)

In Go, keep one Idempotency-Key per logical verification operation, set vendor_data to your stable user id for duplicate detection, and treat a 409 as a state reload, not a retry. A full KYC check costs $0.33.

Idempotent API Calls in Go for Identity Verification (2026)

Contents

In this guide

Jump to the part you need.

Go teams use this guide to make Didit identity verification safe to retry: a create-session call that timed out but succeeded, a webhook delivered twice, a user who ends up with two open sessions. It covers prerequisites, numbered steps, a runnable Go client and a worked cost. Prices are published, and a full KYC check costs $0.33. The main caveat: vendor_data is your duplicate-detection key, so a retry that changes it is a new operation.

Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.

The answer in one table

What a retry-safe Didit integration in Go uses
ItemValue
Endpoint to start a verificationPOST https://verification.didit.me/v3/session/. One endpoint for KYC and KYB; the workflow type decides which session is created
Authenticationx-api-key header holding your Didit API key
Stable entity keyvendor_data, your own id for the person or business. It binds the session to that entity and is used for duplicate detection across sessions
Request keyIdempotency-Key header, one per logical operation, reused unchanged on every retry. Confirm support on each endpoint you retry
Retry these429 after the Retry-After floor plus jitter, 500, 502, 503, up to five attempts
Fix before retrying400, 401, 402, 403, 404, 410, 415, 422
Conflict409, for example a reused Idempotency-Key or a step that already ran. Read code and reload state; the lookup is application-specific
Reading a decisionGET /v3/session/{session_id}/decision/, a GET you can repeat safely
PriceFull KYC check $0.33, AML screening $0.20 per check
Go clientThe standard library net/http, or the official module github.com/didit-protocol/sdk-go (Go 1.22 minimum)

Start free in the sandbox at https://business.didit.me/, no sales call. If you would rather have an AI assistant read sessions and docs while you build, connect Didit to an assistant through https://didit.me/developers/mcp/. We publish prices, plans and the cost estimator on https://didit.me/pricing/, and the endpoint used here is documented in Create Session API.

Why a retried verification call is a real problem

A retry is not a repeat of your intent. It is a second request. If the first one reached Didit and the response was lost on the way back, a naive retry can leave you with two links, two decision objects, two webhook sequences, and an argument about which one is authoritative. Billing is per completed check, so two sessions that both complete cost twice for one intent.

Didit gives you two different controls. vendor_data binds a session to the entity you name and is used for duplicate detection across sessions. An Idempotency-Key is a request key. Our errors documentation lists a reused Idempotency-Key as one possible cause of a 409, next to a step that already ran, and it does not document replay behavior for session creation, so confirm support on each endpoint you retry. The remaining work is in your Go client, which has to send the same values on every attempt and store what came back.

A session overview with its warnings in the Didit Business Console
One session per person is what you want to see here: a single overview with the warnings for that user.

What idempotent means in this integration

Three statements, and nothing more complicated than that.

  • The key comes from your data, not from the attempt. Derive it once from vendor_data plus the operation, write it down, and reuse it for every retry of that operation.
  • The session session_id is stored the moment a 2xx arrives, before you send a notification, write an audit line or reply to the user.
  • Webhook handling is keyed on event_id, because the same event can arrive more than once.

Status values are exact, case-sensitive strings: Not Started, In Progress, Approved, Declined, In Review, Awaiting User, Resubmitted, Expired, Abandoned and Kyc Expired. Compare with strict equality, and note that Kyc Expired uses a single capital K. As a client rule, never write a status that moves a session backwards; read the current status before you write your own.

Prerequisites

  • Go 1.22 or newer if you use the official server SDK. The module is github.com/didit-protocol/sdk-go, installed with go get github.com/didit-protocol/sdk-go.
  • A Didit API key, created in the console under API keys, exported as DIDIT_API_KEY. Every SDK reads that variable, and so should your own client.
  • A workflow UUID from /v3/workflows/. A KYC workflow creates a user verification session, a KYB workflow creates a business verification session. There is no separate KYB endpoint.
  • A stable id for the person or business in your own system, used as vendor_data.
  • If you set a callback, an http or https URL on the application's allowed domains, otherwise creation fails with 400 on callback. Custom URL schemes such as myapp:// are always accepted.
  • A sandbox application for the first run, so the retry you are testing cannot bill a live check.

Steps to make Didit calls idempotent in Go

  1. Create or pick the workflow in the Didit console and copy its UUID. This is workflow_id. Changing workflow versions later does not change the key you will build next.

  2. Choose the value of vendor_data before anything else. Use the id your product already has for the person, so the same value survives restarts, deployments and a support agent retrying by hand.

  3. Build the idempotency key from that same value, for example create-session-<vendor_data>-v1. The version suffix lets you deliberately start a new attempt later, such as a resubmission the user asked for. Store the key next to the user record before the first attempt, because a crash after sending is exactly the case this protects against. Confirm that the endpoint you are retrying documents Idempotency-Key support; this guide uses it on session creation.

  4. Send the request. The program below is one file, runs with go run main.go, and uses only the documented request fields. It retries only on the statuses Didit documents as retryable, honors Retry-After on a 429, adds exponential backoff with jitter, stops after five attempts, parses session_id on success and treats a conflict as a state reload.

    package main
    
    import (
    	"bytes"
    	"encoding/json"
    	"fmt"
    	"io"
    	"math/rand"
    	"net/http"
    	"os"
    	"strconv"
    	"time"
    )
    
    const maxAttempts = 5
    
    type createSession struct {
    	WorkflowID string            `json:"workflow_id"`
    	VendorData string            `json:"vendor_data"`
    	Callback   string            `json:"callback,omitempty"`
    	Metadata   map[string]string `json:"metadata,omitempty"`
    }
    
    func retryAfter(resp *http.Response) time.Duration {
    	v := resp.Header.Get("Retry-After")
    	if v == "" {
    		return 0
    	}
    	if secs, err := strconv.Atoi(v); err == nil {
    		return time.Duration(secs) * time.Second
    	}
    	if t, err := http.ParseTime(v); err == nil {
    		if d := time.Until(t); d > 0 {
    			return d
    		}
    	}
    	return 0
    }
    
    func backoff(attempt int) time.Duration {
    	d := 5 * time.Second
    	for i := 1; i < attempt; i++ {
    		d *= 2
    		if d > 40*time.Second {
    			d = 40 * time.Second
    			break
    		}
    	}
    	jitter := time.Duration(rand.Int63n(int64(d/2))) - d/4
    	if d+jitter < time.Second {
    		return time.Second
    	}
    	return d + jitter
    }
    
    func main() {
    	body := createSession{
    		WorkflowID: os.Getenv("DIDIT_WORKFLOW_ID"),
    		VendorData: "user_8f21c4",
    		Callback:   "https://app.example.com/kyc/return",
    		Metadata:   map[string]string{"signup_id": "s_1042"},
    	}
    	payload, err := json.Marshal(body)
    	if err != nil {
    		panic(err)
    	}
    
    	// One key per logical operation. Store it before the first attempt and reuse it on every retry.
    	key := "create-session-user_8f21c4-v1"
    
    	client := &http.Client{Timeout: 10 * time.Second}
    	for attempt := 1; attempt <= maxAttempts; attempt++ {
    		req, err := http.NewRequest(http.MethodPost, "https://verification.didit.me/v3/session/", bytes.NewReader(payload))
    		if err != nil {
    			panic(err)
    		}
    		req.Header.Set("x-api-key", os.Getenv("DIDIT_API_KEY"))
    		req.Header.Set("Content-Type", "application/json")
    		req.Header.Set("Idempotency-Key", key)
    
    		resp, err := client.Do(req)
    		if err != nil {
    			fmt.Printf("attempt %d: transport error: %v\n", attempt, err)
    			if attempt == maxAttempts {
    				break
    			}
    			wait := backoff(attempt)
    			fmt.Printf("waiting %s before retry\n", wait)
    			time.Sleep(wait)
    			continue
    		}
    		raw, _ := io.ReadAll(resp.Body)
    		resp.Body.Close()
    
    		switch {
    		case resp.StatusCode/100 == 2:
    			var out struct {
    				SessionID string `json:"session_id"`
    				Status    string `json:"status"`
    			}
    			if err := json.Unmarshal(raw, &out); err != nil {
    				fmt.Printf("attempt %d: %d, response did not parse: %s\n", attempt, resp.StatusCode, raw)
    				return
    			}
    			if out.SessionID != "" {
    				// Persist the session id before notifying anyone. Replace this file with your own datastore.
    				_ = os.WriteFile("session_id.txt", []byte(out.SessionID), 0600)
    			}
    			fmt.Printf("attempt %d: %d session_id=%s status=%s (stored in session_id.txt)\n", attempt, resp.StatusCode, out.SessionID, out.Status)
    			return
    		case resp.StatusCode == http.StatusConflict:
    			// Application-specific: load the session id you stored for this vendor_data and return that state.
    			// This sample returns so a conflict never becomes a retry loop.
    			fmt.Printf("attempt %d: 409 conflict, reload the state you stored: %s\n", attempt, raw)
    			return
    		case resp.StatusCode == http.StatusTooManyRequests:
    			floor := retryAfter(resp)
    			wait := backoff(attempt)
    			if wait < floor {
    				wait = floor + time.Duration(rand.Int63n(int64(floor/4+1)))
    			}
    			fmt.Printf("attempt %d: 429, waiting %s (Retry-After floor %s)\n", attempt, wait, floor)
    			if attempt == maxAttempts {
    				break
    			}
    			time.Sleep(wait)
    			continue
    		case resp.StatusCode >= 500:
    			wait := backoff(attempt)
    			fmt.Printf("attempt %d: %d, waiting %s\n", attempt, resp.StatusCode, wait)
    			if attempt == maxAttempts {
    				break
    			}
    			time.Sleep(wait)
    			continue
    		default:
    			fmt.Printf("attempt %d: %d, fix the request: %s\n", attempt, resp.StatusCode, raw)
    			return
    		}
    	}
    	fmt.Printf("giving up after %d attempts\n", maxAttempts)
    }
    
    export DIDIT_API_KEY="your_key"
    export DIDIT_WORKFLOW_ID="your_workflow_uuid"
    go run main.go
    
  5. Read the response and keep session_id. A 2xx means a session exists. The sample parses session_id and writes it to session_id.txt; in production write it to your own datastore before you do anything else, then hand the session link to the user.

  6. Handle 409 as a lookup, not a retry. It means the key was already used or the step already ran. The sample stops on a conflict; the actual reload is application-specific: look up the session id you stored for vendor_data and return that state. Retrying the same body in a loop is how teams turn one conflict into a rate-limit incident.

  7. Back off on 429. Didit sends Retry-After only on a 429, plus X-RateLimit-Scope, X-RateLimit-Limit and X-RateLimit-Reset. Use Retry-After as the floor, layer exponential backoff with jitter on top, and stop after five attempts; the code above does exactly that. POST /v3/session/ allows 600 requests a minute per API key, and one key shared across many backends shares that counter.

  8. Verify and deduplicate webhooks. Read the raw body before parsing, recompute the HMAC-SHA256 signature (X-Signature-V2 is the recommended header), reject anything where X-Timestamp is more than 300 seconds from now, then deduplicate on event_id, return 2xx quickly and apply the change idempotently.

  9. Read the decision with GET /v3/session/{session_id}/decision/ when you need the current state. It is a GET, so repeating it is safe, and it is governed by the generic GET ceiling of 600 requests a minute rather than the 100 a minute decision throttle that applies to the v1 and v2 decision paths.

Illustrative output from the run above, with placeholder ids and timings:

attempt 1: 201 session_id=<uuid> status=Not Started (stored in session_id.txt)

Run it twice with the same key and record the status and the body of the second response. That record is the check that matters, and it is the first line of the go-live packet below.

Inputs and outputs

Fields on POST /v3/session/ and what comes back
FieldTypeWhat it does
workflow_idstring, UUID, requiredStable workflow UUID from /v3/workflows/. KYC workflows create user sessions, KYB workflows create business sessions
vendor_datastring, optional, send itYour stable identifier for the entity. Binds the session to a user or business and is used for duplicate detection across sessions
callbackURL, optionalWhere the hosted flow redirects the user when finished. Didit appends verificationSessionId and status. Must be on the application's allowed domains for http and https
callback_methodstring, optionalinitiator, completer or both. Use both if the callback sometimes fails to fire
metadataobject, optionalArbitrary JSON echoed back in responses and webhooks, never shown to the user
tagsarray of strings, optionalUp to 10 tags, each up to 50 characters, added at creation and returned in the create response
session_expiration_timeinteger, optionalSeconds the link stays valid, between 3600 and 2419200. Outside that range returns 400
languagestring, optionalISO 639-1 code for the verification UI
What comes back
OutputWhereUse
session_idCreate response, webhooksYour durable handle for this verification. Store it against vendor_data
statusCreate response, decision, webhooksOne of the exact status strings. Not Started is normal right after creation
event_idWebhook envelopeThe deduplication key for webhook handling
webhook_typeWebhook envelopeFor verification work you subscribe to status.updated, and data.updated when verification data is edited
decisionWebhook and decision endpointPer-feature results in plural arrays such as id_verifications, liveness_checks, face_matches, aml_screenings

Failure cases and recovery

Didit reports a failure with an HTTP status and, in almost every case, a JSON body. Branch on the status first and on code when it is present, because message text can change.

Status codes and what your Go client should do
StatusMeaningAction
400The request is invalid, for example a bad callback origin or an out-of-range session_expiration_timeFix the body, then send again
401The key is wrong, malformed, revoked or expiredCheck DIDIT_API_KEY or create a new key
402The check could not be paid for, so it did not runTop up, then retry
403No key, no access to this resource, an IP outside the key's list, or a balance that cannot cover the callRead the body, fix access or balance
404The resource does not exist, or the session sits outside the key's workflow or status limitsDo not retry. Check the id and the key limits
409Conflict with current state, such as a reused Idempotency-Key or a step that already ranRead code and reload state. Retry only if the code says so
410The resource expired, for example a session or an invitationCreate a new session with a new key
415The body is not JSONSend Content-Type: application/json
422A wallet address fits more than one blockchain, so nothing was screened or billedResend with blockchain set to one of candidate_chains
429A rate limit or quota was reachedWait for Retry-After, then retry with jitter
500An unexpected error on Didit's sideRetry with backoff. A 500 may have no JSON body, so handle unparseable bodies
502 / 503A dependency errored, is unavailable, or the request timed out with query_timeoutRead code and retry
AML screening result for a session in the Didit Business Console
The screening result behind one session. A retried webhook must not create a second copy of this record.

Billing is per completed check from prepaid credit, so the retry discipline above is also a billing control. Free on every plan: the sandbox, Reusable KYC, the Workflow Orchestrator, the MCP server and the SDKs. The free plan also includes $10.00 of credit every month for organizations that sign up with a work email, with phone codes excluded, and unused monthly credit does not roll over.

Paid lines you are likely to touch: full ID check $0.33, ID document verification alone $0.15, passive liveness $0.10, active liveness $0.15, face match 1:1 $0.05, device and IP analysis $0.03, AML screening $0.20 per check, ongoing AML monitoring $0.07 per user a year, proof of address $0.20, NFC chip reading $0.15 as an add-on. Business verification is priced by country and data tier from $2.00 per company, with a linked full ID check and person AML billed per person, and wallet screening $0.15 per screening.

Where a person decides: automated checks move a session to Approved, Declined or In Review. In Review means a compliance reviewer must open the session in the console and approve, decline or request a resubmission, and only a reviewer or the update-status endpoint can move a decided session afterwards. No amount of retrying changes a decision, and a retry that returns a decision you did not expect means you are reading a different session or a stale key.

Worked cost example

A consumer app verifies 10,000 users a month with a KYC workflow, then screens each approved user against AML lists once.

  • Full ID check: $0.15 ID document + $0.10 passive liveness + $0.05 face match + $0.03 device and IP = $0.33 per check.
  • KYC only: 10,000 x $0.33 = $3,300.00.
  • KYC plus AML screening: $0.33 + $0.20 = $0.53 per person, so 10,000 x $0.53 = $5,300.00.
  • On Growth, the 4% discount applies to Didit prices: $0.33 x 0.96 = $0.3168, so 10,000 x $0.3168 = $3,168.00.
  • On Scale, the 10% discount: $0.33 x 0.90 = $0.297, so 10,000 x $0.297 = $2,970.00.

Retries do not add to those totals when they are done right. A retry that lands on 409, 429 or 400 creates no new completed check. A retry that creates a second session, and that session then completes, is a completed check and is billed like any other. That is the arithmetic that makes the key discipline worth the hour it takes.

How Didit billing works: credits, auto-recharge and volume discounts
Credits and volume discounts explained, which is where the per-check prices above turn into a monthly bill.

The customer-safe go-live packet for retries, idempotency, and first-value checks

Before traffic, hand a reviewer these five artifacts. Each one is a check someone else can run without reading your code.

  1. The key format, written down: how vendor_data and the operation name produce the Idempotency-Key, and when the version suffix changes.
  2. The retry list: the exact statuses you retry, the backoff you apply, and the attempt ceiling. Anything outside that list fails loudly.
  3. A sandbox run where the same key is sent twice, with both responses saved and the status and body of the second one explained.
  4. One delivered webhook with a verified X-Signature-V2, replayed a second time, producing no duplicate state change.
  5. The first-value check: a new user completes a sandbox KYC workflow and your system shows the correct status from the decision endpoint without anyone reading a log.

Sources

Create a free organization at https://business.didit.me/, run the program above twice with the same key, and record the status and body of the second response. No sales call is involved, and the sandbox run costs nothing.

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

Alejandro Rosas

Co-founder and CTO

Alejandro Rosas

Alejandro Rosas

Co-founder and CTO

About Didit

Questions

Frequently asked questions

Is the Didit API idempotent?

Didit gives you two separate controls. vendor_data ties a session to your entity and is used for duplicate detection across sessions. Our errors documentation lists a reused Idempotency-Key as one possible cause of a 409, next to a step that already ran, and it does not document replay behavior for session creation, so confirm support on each endpoint you retry. Your client still has to reuse the same key on every retry, because a new key is a new request.

What is an idempotency quickstart for go-live teams?

Do three things in one sitting, all free in the sandbox: install the Go client, create one sandbox session with a key derived from vendor_data, then send the identical request a second time and record the status and the body of that second response. Keep the key and vendor_data unchanged between the two runs, treat a 409 as a state reload rather than a retry, and read the result with GET /v3/session/{session_id}/decision/.

Which Didit API calls are safe to retry in Go?

Retry 429 after waiting for Retry-After, and retry 500, 502 and 503 with exponential backoff and jitter, stopping after five attempts. Do not retry 400, 401, 402, 403, 404, 410, 415 or 422 until you have fixed what the body names. Treat 409 as a state reload and only retry if the returned code says so.

What does a 409 mean when creating a session in Go?

It means the request conflicts with current state, most often a reused Idempotency-Key or a step that already ran. Read the code field, load the session id you stored for vendor_data, and return that state. The lookup is application-specific; do not retry the same body in a loop.

Do retries cost money with Didit?

A retry that lands on 409, 429 or a validation error creates no new completed check, so nothing new is billed. A retry that creates a second session which then completes is a completed check and is billed at the module prices, $0.33 for a full KYC check and $0.20 for AML screening. That is the practical reason to key retries on your own user id.

Which endpoint does a Go client call to start an identity verification?

POST https://verification.didit.me/v3/session/ with the x-api-key header and a workflow_id. A KYC workflow creates a user verification session and a KYB workflow creates a business verification session, so there is no separate KYB endpoint to remember.

Does the Didit Go SDK cover every endpoint?

The module is github.com/didit-protocol/sdk-go and needs Go 1.22 or newer. The Go 1.0.1 line does not have the two Google Wallet endpoints, and it lacks nine more, most of them Travel Rule endpoints; the Python, Node.js, Java, PHP, Ruby and .NET SDKs have every other server endpoint. For anything missing, call the documented REST endpoint from net/http exactly as the sample above does.

How do I keep Didit webhooks idempotent?

Read the raw body before parsing, recompute the HMAC-SHA256 signature, and accept X-Signature-V2 (and its previous header during a secret rotation). Reject timestamps more than 300 seconds old, deduplicate on event_id, return 2xx quickly, and re-fetch the decision rather than trusting a payload you verified only at envelope level. There is no wildcard subscription, so list every event family you want, starting with status.updated.

What happens if a session expires before the user starts?

The session moves to Expired, and a request against an expired resource returns 410. Create a new session with a new key rather than reusing the old one, because the old logical operation is closed and the old key will keep answering with a conflict.

Can I test all of this without paying?

Yes. The sandbox is free and unlimited on every plan, and sandbox applications accept a sandbox_scenario so you can reproduce a specific outcome without touching live checks. The free plan also includes $10.00 of monthly credit for eligible organizations, which is enough to run a small live pilot after the sandbox checks pass.

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.