Video in progress

How do you design storing idempotency keys for a payment API in Redis, and where do you see the risks?

I claim the key with SET NX in an "in progress" state, write the result to that key, and return the saved response for a repeated request. But a write in Redis can be lost on failover, so for money movement the real guarantee must be a unique constraint in the DB, and Redis is a fast filter.

📖 Answer

On every payment request the client sends an Idempotency-Key header. If the network drops, it resends with the same key.

The flow:

String key = "idem:payments:" + merchantId + ":" + idemKey;
Boolean first = redis.opsForValue()
        .setIfAbsent(key, "{\"state\":\"IN_PROGRESS\"}", Duration.ofHours(24));

if (Boolean.FALSE.equals(first)) {
    IdemRecord r = read(key);
    if (r.inProgress()) throw new ConflictException("So'rov hali bajarilmoqda"); // 409
    if (!r.requestHash().equals(hash(body))) throw new UnprocessableException(); // 422
    return r.response(); // the previous response
}
try {
    PaymentResponse resp = paymentService.charge(cmd);
    save(key, IdemRecord.done(hash(body), resp));
    return resp;
} catch (RetryableException e) {
    redis.delete(key); // let the client retry
    throw e;
}

Design decisions:

  • I put the merchant/user ID in front of the key so it doesn't collide with another client;
  • the hash of the request body is stored: if a different amount arrives with the same key, it's an error, not a silent replay;
  • the "in progress" state needs a TTL, otherwise if a pod dies the key is blocked forever; but if the TTL expires and a second request starts, the first one may actually have finished;
  • maxmemory-policy must be noeviction on this cluster: if LRU deletes idempotency keys, the guarantee silently disappears.

Where the risks are:

  • losing the latest writes on failover: a repeated request goes through as the "first";
  • charge succeeds, but the pod dies before writing the result: the key stays "in progress" and the outcome is unknown.

That's why I build two layers: Redis is the fast path and blocks concurrent duplicates; a unique index on payments(merchant_id, idempotency_key) in the DB is the real guarantee, with the payment and the key written in one transaction. For requests in an unknown state, you need a reconciliation job that checks the state on the provider's side. If Redis goes down, the system slows down, but it doesn't charge twice.