Idempotent usage events: keys, dedupe windows and late arrivals
Your API gateway sends a usage event to billing for every request. At 23:58 on 31 August a batch of 2,000 events times out. The client retries, but the first upload had already landed. Meanwhile some events from 31 August are stuck in a backed-up queue and only arrive on 2 September, after the August invoice has been finalised. Without clear rules the customer now pays for 2,000 requests twice, and the late ones either vanish or end up on the wrong invoice.
This article covers three decisions you have to make explicitly in usage-based billing: what an event's idempotency key consists of, how long you remember it, and what happens to events that arrive after the period has closed.
The key is created by the producer
A usage event needs an identifier that stays the same on every retry. The receiver's database ID won't do, and neither will the arrival time: both are new on a retry. The key has to be created where the event happens, which means in the producer.
Good candidates are identifiers that already exist: the gateway's request ID, a batch job's run ID, a transaction ID. The producer derives an event_id from these, stores it and sends it unchanged on every retry. The CloudEvents specification takes the same approach: an event is unique by the combination of source and id. That's worth copying even if you don't use the CloudEvents format, because two systems can then generate the same request ID without deduplicating each other.
Two mistakes in producer code are typical:
- The ID is regenerated on the retry path, for example with
uuid4()inside the send function. Every retry is then a new event. - Several business operations share one ID, for example because a batch has only one identifier. The receiver then drops real events as duplicates. Each event in a batch needs its own
event_id.
HTTP APIs can also use the Idempotency-Key header, described in the IETF draft on the Idempotency-Key header. It protects a single request. For batches the per-event event_id matters more, because a batch may have been partly accepted.
Deduplicate with a unique key in the database
"Check first, then insert" breaks under load. Between the SELECT and the INSERT, a second worker can write the same event. The only safe option is a database constraint that detects the conflict atomically:
CREATE TABLE usage_events (
source TEXT NOT NULL,
event_id TEXT NOT NULL,
customer_id TEXT NOT NULL,
meter TEXT NOT NULL,
quantity NUMERIC NOT NULL,
occurred_at TIMESTAMP NOT NULL,
received_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
payload_hash TEXT NOT NULL,
PRIMARY KEY (source, event_id)
);
INSERT INTO usage_events (source, event_id, customer_id, meter, quantity, occurred_at, payload_hash)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (source, event_id) DO NOTHING
RETURNING event_id;
If RETURNING gives no row, the event was already there. Then compare payload_hash with the stored value. Same hash: a harmless retry, answer "accepted". Different hash: the producer reused an ID for different content. That's a producer bug and belongs in monitoring, not in a silent drop.
The ratio of duplicates to new events is a useful metric. If it jumps, a client has usually changed its retry logic or a queue is redelivering messages.
How long to remember keys
The table grows. At some point you'll want to delete or archive old keys, and from then on a late duplicate can no longer be detected. This dedupe window has to be longer than the longest period in which a producer can still retry.
An example: the gateway client retries for up to 24 hours, but a batch job restarted by hand after an outage can resend a whole week of events. A 48-hour window then protects only the gateway. So set the window per source and document it with the producer as a contract: "After seven days, retries are counted as new events."
A pragmatic rule of thumb is to keep keys at least until the invoice for that period has been finalised. While the invoice is still a draft, any mistake can be corrected. You'll usually need the raw data itself for longer, so that an invoice line can later be traced back to its events.
Store usage time and arrival time separately
occurred_at is when the usage happened, received_at when billing received it. Price and period follow the usage time. An event from 31 August that arrives on 2 September is August usage. You need the arrival time for operations and audit: it shows how late a producer is and later explains why a quantity wasn't on the first invoice.
Watch the time zones. Store both values in UTC and set the period boundary per customer. A customer billed on German time has their month-end two hours before midnight UTC in summer. An event at 23:30 UTC on 31 August already belongs to September for them.
Late events after the period closes
Late events need two rules: a grace period before finalisation, and a rule for everything that arrives after it.
The grace period keeps the invoice in draft for a while after the period ends, so late events flow in without a correction. How long it should be depends on the source: gateway events usually arrive within minutes, usage from nightly exports only the next day.
Anything arriving after finalisation must not change that invoice. There are two ways to carry it forward:
| Case | Handling | On the document |
|---|---|---|
| Small late quantity | Charge on the next invoice | Separate line with service period August |
| Large deviation or customer query | Credit note or supplementary invoice for August | Reference to the original invoice, service period August |
| After the dedupe window has expired | Accept with a warning, manual review | Only after approval |
The service period is what matters. If you bill August usage on the September invoice, the line has to carry August as its service period, because the EU VAT Directive requires invoices to show the date of supply where it differs from the invoice date. And if prices changed on 1 September, the August price applies. Billing therefore has to know which price version was valid in August; see product catalogue versioning.
One test that covers all three rules
Run this sequence against your own billing system or a vendor's sandbox:
- Send 100 events with unique IDs, then the same 100 again. Expected: quantity 100.
- Send an event with a known ID but a changed quantity. Expected: rejection or conflict, quantity stays 100.
- Send 50 new events, each one from ten parallel workers at once. Expected: quantity 150.
- Send an event with
occurred_aton the last day of the period after the grace period has ended. Expected: the finalised invoice is unchanged, and a catch-up line appears with the old service period. - Retry an event after the dedupe window has expired. Expected: a warning, not a silent double count.
If all five results hold, you can trust the quantities on the invoice. How Kontier models usage-based tariffs is described on the usage-based billing page.
Not tax or legal advice. This post describes the law and common practice in general terms. For your own case, ask your tax adviser. As of: