[SKIP TO CONTENT]
LAST_UPDATE: 23 November 2026
Go back
BY Junrong Li

> Designing a Token-Based Credit System for AI Applications

Preventing duplicate requests, double deductions, and lost work with idempotency, processing leases, and transactional messaging.

Imagine an AI product with a prepaid credit balance. Users buy credits, submit prompts, and spend credits according to the tokens their requests consume. The happy path is easy to describe: accept a prompt, ask the model for a response, count the tokens, and subtract the corresponding credits.

The difficult questions start when something goes wrong:

These are not merely technical edge cases. They translate into duplicate charges, free usage, stuck requests, confusing support tickets, and lost customer trust.

In this article, I explore a design for handling these failures. The principles apply regardless of programming language, message broker, database library, or LLM provider.

1. Start with the business contract

Before introducing queues or workers, define the behavior customers should observe:

  1. One submission, one logical operation. Retrying a request must not create a second billable job.
  2. A trustworthy balance. Two concurrent requests must not spend the same prepaid credits.
  3. Recoverable processing. A server crash should not leave jobs stuck forever.
  4. A durable link between results and credit settlement. If a result is committed, the corresponding credit-settlement work must not vanish.
  5. One settlement per operation. A retry or duplicate message must not deduct credits twice.

One distinction matters throughout this design: one logical operation is not the same thing as exactly one call to an external LLM. I return to that distinction later.

The tempting happy-path design

flowchart TD
    A[User submits prompt] --> B[Call LLM provider]
    B --> C[Save AI response]
    C --> D[Deduct credits]
    D --> E[Return result]

This works when every component succeeds exactly when expected. It does not define what happens during concurrency, retries, or partial failure.

2. Duplicate submissions: identify the logical request

Suppose a user clicks Send twice, or an external API caller times out and retries. Both HTTP requests may reach the backend almost simultaneously. Disabling a button helps the user experience, but it is not a correctness guarantee: clients can retry, use multiple tabs, or call the API directly.

The solution is an idempotency key: a unique identifier for a logical submission.

For example:

POST /api/chat
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
Content-Type: application/json

{"conversationId":"conv-42","prompt":"Explain CQRS"}

The server should not rely on this fragile pattern:

IF request does not exist:
    INSERT request
    START AI job

Two requests can both observe “does not exist” before either inserts. This is a classic check-then-act race condition.

Instead, let the database atomically claim the key using a unique constraint. A conceptual PostgreSQL-style statement is:

INSERT INTO ai_requests (
    request_id, client_id, idempotency_key,
    request_hash, status
)
VALUES (
    @RequestId, @ClientId, @IdempotencyKey,
    @RequestHash, 'pending'
)
ON CONFLICT (client_id, idempotency_key) DO NOTHING
RETURNING request_id;

Here request_id is an internal identifier and (client_id, idempotency_key) has a unique constraint. The request hash represents the canonicalized, business-relevant input—not just the prompt text.

flowchart TD
    A[Request A: key K] --> C[Atomic request registration]
    B[Request B: key K] --> C
    C --> D{Was a new row inserted?}
    D -->|Yes| E[Reserve credits and persist job]
    D -->|No| F[Read existing request]
    F --> G{Same client and payload?}
    G -->|Yes| H[Return original request ID and status]
    G -->|No| I[Reject conflicting key reuse]

The unique constraint prevents duplicate registration, even across multiple API servers. When the first transaction is still uncommitted, a competing insert may wait until its outcome is known.

A useful API response is an operation identifier plus its status. A first submission might return 202 Accepted with requestId=R; a legitimate retry can return the same R, not create a new job. The client then polls GET /api/chat/requests/R or subscribes to progress updates.

Boundary: A client that creates two different keys has requested two distinct logical operations. If your product permits only one active generation per conversation, enforce that as a separate business rule.

3. Protect the balance before calling the model

Idempotency alone does not prevent overspending.

Suppose a customer has 1,000 credits available and submits two distinct requests at the same time. Each could cost up to 800 credits. If both check the balance before either reserves funds, both may pass even though the account cannot fund both requests.

A safer model is reserve → generate → settle:

  1. Reserve a defined maximum or budgeted charge before beginning generation, using an atomic balance update in a database transaction.
  2. Generate the response within that budget. Enforce a token/output limit or another policy so the final cost cannot silently exceed the reservation.
  3. Settle based on the provider’s reported usage and your model-specific price rules; release any unused reservation. If generation fails, apply a documented release or partial-charge policy.

For a simple wallet, maintain available and reserved credits. The reservation must be atomic—never just “read balance, then subtract” in separate unprotected operations.

EventAvailableReserved
Initial balance1,0000
Reserve up to 500500500
Model usage costs 350500500
Settle and release remainder6500

A separate credit ledger records the actual financial movement. Give each settlement a unique business identifier, typically the AI request_id, and make recording that settlement and updating the wallet one database transaction. A unique ledger row without an atomic balance update is not enough to prevent double charging.

If the provider can consume tokens or incur fees outside your reserved budget, decide explicitly whether to stop generation, require additional funds, or absorb the excess cost.

4. A queue helps reliability—but it does not mean exactly once

Long-running AI calls are natural background jobs. An API can accept the request, persist the work, and let a worker generate the response while the client tracks progress.

However, queues commonly provide at-least-once delivery: a message can be delivered again if a worker crashes or an acknowledgement is lost. It is unsafe to assume “one queued message means one execution.”

A worker should atomically claim the business request before invoking the LLM:

UPDATE ai_requests
SET status = 'processing',
    started_at = NOW()
WHERE request_id = @RequestId
  AND status = 'pending'
RETURNING request_id;

Only the worker that successfully transitions the row may proceed. A concurrent worker sees that the status no longer matches and must not start another LLM call.

flowchart TD
    Q[Queue delivers job R] --> W[Worker attempts atomic claim]
    W --> D{Claim succeeded?}
    D -->|No| S[Do not start another generation]
    D -->|Yes| L[Invoke LLM]
    L --> P[Persist result and usage]

This protects against concurrent claims under normal operation. But a permanent processing flag creates another problem: what happens if the worker dies?

5. Recover crashed workers with a lease

A processing lease is a time-limited claim on a job. Store the current lease owner (a random token), its expiration, and an attempt count. A worker can claim a pending job or reclaim one whose lease has expired.

pending ──claim──> processing ──success──> generated
                      │
                      ├──failure policy──> failed / retryable
                      │
                      └──lease expires──> eligible for recovery

While generating, a healthy worker renews the lease. To complete, it must prove it still owns the current lease—for example, with a conditional database update using the lease token. This is called fencing: an old worker cannot overwrite a newer worker’s committed result.

sequenceDiagram
    participant DB as Job database
    participant A as Worker A
    participant L as LLM provider
    participant B as Worker B
    A->>DB: Atomically claim R, lease token A
    DB-->>A: Claim accepted
    A->>L: Generate response
    Note over A: Worker crashes or stops renewing
    Note over DB: Lease expires
    B->>DB: Reclaim R, lease token B
    DB-->>B: Claim accepted
    B->>L: Generate or reconcile per policy
    B->>DB: Complete R only if token B owns lease

A crucial limit: The expiry of a lease does not prove that Worker A’s external LLM call stopped. A slow or disconnected worker might still be running. Worker B could trigger another provider call, even though fencing protects the database from stale writes.

This is why recovery needs policy, not merely a timer:

Do not hold a database transaction open during the network call to the LLM.

6. Saving a result and requesting credit settlement must be atomic

Now imagine the worker receives a successful model response and knows its token usage. I will use a separate background worker for credit settlement in this example.

A naive implementation does this:

1. Save AI result to database   ✅
2. Application crashes         ❌
3. Send credit-settlement command        Never happens

The response exists, but the credit-settlement worker never hears about it. Retrying the original generation job may not help if your business logic correctly refuses to regenerate an already saved result.

This is the dual-write problem: one logical business change spans a database commit and a message delivery, with a crash window between them.

The transactional outbox solves it by saving both the AI result and an outgoing credit-settlement instruction in the same database transaction. A separate dispatcher then sends the persisted message to the queue.

flowchart TD
    A[LLM response and token usage ready] --> T
    subgraph T[Single database transaction]
      B[Save AI result and usage]
      C[Persist SettleCredits message in outbox]
    end
    T --> D{Commit succeeds?}
    D -->|No| E[Neither change is committed]
    D -->|Yes| F[Outbox dispatcher]
    F --> G[Credit-settlement queue]
    G --> H[Idempotent settlement worker]
    H --> I[Record ledger and update wallet atomically]

If the system crashes after the transaction commits but before queue delivery, the message remains in the outbox for later dispatch. If delivery happens twice, the settlement worker must detect the duplicate by request_id and avoid a second settlement.

Outbox prevents a lost instruction; inbox/deduplication and database constraints prevent duplicate effects. The two patterns complement each other.

An alternative, often simpler for a single application, is to save the result and settle the credits in one local database transaction, then publish non-critical analytics or notification events. A separate settlement queue is useful when credit management is independently operated, scales separately, or requires its own retry workflow—not because every deduction inherently needs a queue.

7. End-to-end architecture

Here is how I put the pieces together into one workflow:

flowchart TD
    U[User or API client submits prompt] --> K[Attach idempotency key]
    K --> API[API validates caller, payload and key]
    API --> REG{Atomic registration: new request?}
    REG -->|No, same payload| EXIST[Return original request ID and status]
    REG -->|No, different payload| CONFLICT[Reject key conflict]
    REG -->|Yes| TX[Transaction: reserve credits and persist job in outbox]
    TX --> Q[Durable job queue]
    Q --> CLAIM{Worker claims valid lease?}
    CLAIM -->|No| SKIP[Skip duplicate delivery]
    CLAIM -->|Yes| LLM[Call LLM within budget]
    LLM --> SAVE[Transaction: fence lease, save result and usage, persist settlement command]
    SAVE --> BILL[Settlement worker updates ledger once]
    BILL --> DONE[Mark fully settled; publish status]
    EXIST --> TRACK[Client tracks existing job]
    DONE --> TRACK

The exact order of generated, settlement_pending, and completed states depends on your product promise. If the product promises an up-to-date balance when a result is labeled completed, do not mark it fully completed until settlement commits. If settlement is asynchronous, expose generation and settlement statuses separately.

Design checklist

Failure or riskPrimary safeguard
Double-click or HTTP retryClient-generated key, unique database registration
Same key with different inputAuthenticated client scope plus payload fingerprint
Multiple workers receive one jobAtomic conditional task claim
Worker crashes or stallsExpiring lease, renewal, fencing, recovery policy
Concurrent spendingAtomic credit reservation before generation
Result saved but settlement command lostTransactional outbox
Settlement message delivered twiceUnique ledger settlement and atomic wallet update
External LLM outcome uncertainTimeouts, provider support where available, reconciliation policy

8. What I can—and cannot—guarantee

A careful architecture gives strong business-level guarantees:

But I would not promise exactly-once external LLM execution across arbitrary crashes. A model call may succeed just before the worker loses the response or crashes. Without provider support to recover that exact result, the application cannot always know whether it is safe to call again.

The realistic goal is effectively-once business outcomes on top of systems that may retry or redeliver messages. That means controlling the things the application can control—database state, credit settlement, message persistence—and explicitly handling uncertainty at the external boundary.

Conclusion

The first version of a token-based credit system often looks like a simple pipeline: call the model, count tokens, deduct credits. A production system is a collection of agreements about identity, concurrency, money, and failure.

A reliable design starts with an idempotency key to identify a logical operation, a database uniqueness constraint to register it once, a reservation to protect prepaid balances, a leased worker to coordinate generation, a transactional outbox to preserve downstream work, and an idempotent ledger to settle charges once.

None of these mechanisms replaces the others. Together, they make an AI product more predictable for customers and more operable for the team building it.

In a future post, I’ll turn this architecture into a practical .NET implementation using Wolverine, PostgreSQL-backed messaging, worker leases, and integration tests to demonstrate how to handle duplicate requests and recover from failures.

TAGGED_NODES: