CREATE TABLE idempotency_keys (
id BIGSERIAL PRIMARY KEY,
idempotency_key TEXT NOT NULL,
request_path TEXT NOT NULL,
request_fingerprint TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'in_progress',
response_code INTEGER,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
locked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT idempotency_keys_status_chk
CHECK (status IN ('in_progress', 'completed')),
CONSTRAINT idempotency_keys_unique
UNIQUE (idempotency_key, request_path)
);
-- Background sweeper reaps stale in_progress rows and expired records.
CREATE INDEX idempotency_keys_sweep_idx
ON idempotency_keys (status, locked_at);
const crypto = require('crypto');
const db = require('./db');
function fingerprint(req) {
const payload = JSON.stringify({ method: req.method, body: req.body || {} });
return crypto.createHash('sha256').update(payload).digest('hex');
}
function idempotency() {
return async function (req, res, next) {
const key = req.get('Idempotency-Key');
if (!key) {
return res.status(400).json({ error: 'Idempotency-Key header required' });
}
const path = req.baseUrl + req.path;
const fp = fingerprint(req);
const inserted = await db.query(
`INSERT INTO idempotency_keys (idempotency_key, request_path, request_fingerprint)
VALUES ($1, $2, $3)
ON CONFLICT (idempotency_key, request_path) DO NOTHING
RETURNING id`,
[key, path, fp]
);
if (inserted.rowCount === 0) {
const existing = (await db.query(
`SELECT status, response_code, response_body, request_fingerprint
FROM idempotency_keys
WHERE idempotency_key = $1 AND request_path = $2`,
[key, path]
)).rows[0];
if (existing.request_fingerprint !== fp) {
return res.status(422).json({ error: 'Idempotency-Key reused with different payload' });
}
if (existing.status === 'in_progress') {
res.set('Retry-After', '1');
return res.status(409).json({ error: 'Request already in progress' });
}
return res.status(existing.response_code).json(existing.response_body);
}
const originalJson = res.json.bind(res);
res.json = function (body) {
db.query(
`UPDATE idempotency_keys
SET status = 'completed', response_code = $1, response_body = $2
WHERE idempotency_key = $3 AND request_path = $4`,
[res.statusCode, body, key, path]
).catch(() => {});
return originalJson(body);
};
next();
};
}
module.exports = idempotency;
const express = require('express');
const idempotency = require('./idempotencyMiddleware');
const { createCharge } = require('./charges');
const router = express.Router();
router.post('/charges', idempotency(), async (req, res) => {
const { amount, currency, source } = req.body;
if (!amount || !currency || !source) {
return res.status(400).json({ error: 'amount, currency and source are required' });
}
const charge = await createCharge({ amount, currency, source });
// res.json here is the wrapped version that caches the response.
return res.status(201).json({
id: charge.id,
amount: charge.amount,
currency: charge.currency,
status: charge.status
});
});
module.exports = router;
This snippet implements the Idempotency-Key pattern for unsafe HTTP requests in an Express API. The idea is simple but easy to get wrong: when a client retries a POST (a timeout, a dropped connection, a double-click), the server must recognize the retry and return the original response instead of performing the side effect twice. This is essential for anything money-related — charging a card, creating an order — and for any endpoint fronted by an at-least-once delivery system like a webhook sender.
The migrations/idempotency_keys.sql tab defines the durable store. Each row is keyed by a composite UNIQUE on (idempotency_key, request_path) so the same key can safely appear on different endpoints. A request_fingerprint column records a hash of the request body, letting the middleware detect the dangerous case where a client reuses a key with a different payload. The status column models a small state machine (in_progress then completed), and response_code/response_body cache the eventual reply.
In idempotencyMiddleware.js, the flow begins with an atomic INSERT ... ON CONFLICT DO NOTHING. If the insert wins, this is the first time the key is seen and the request proceeds. If it conflicts, an existing record is loaded: a completed record replays the stored status and body verbatim, while an in_progress record means a concurrent request is still running, so the middleware returns 409 to signal the client to retry later. A mismatched request_fingerprint yields 422, since replaying under a conflicting body would be incorrect.
The clever part is capturing the response. The middleware wraps res.json so that when the handler finally responds, the real status code and body are persisted back into the row and the record is flipped to completed. This makes the cache self-populating without the route handlers knowing anything about idempotency.
The payments route tab shows the payoff: router.post('/charges', ...) mounts the middleware and writes an ordinary handler. Note the trade-offs — the store needs a TTL sweep, the fingerprint uses a stable JSON serialization, and in_progress rows from crashed requests should be reaped by a background job. Used carefully, this turns retries from a liability into a safe default.
Related snips
timestamp = request.headers.fetch('X-Signature-Timestamp')
signature = request.headers.fetch('X-Signature')
payload = request.raw_post
data = "#{timestamp}.#{payload}"
expected = OpenSSL::HMAC.hexdigest('SHA256', ENV.fetch('WEBHOOK_SECRET'), data)
HMAC signed API requests for webhook and partner integrity
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
Share this code
Here's the card — post it anywhere.