API quota: accounting for concurrent requests without duplicate charges

A monthly budget, reservation before reading, request replay, and quota refunds only after an established outcome.

A separate place for a token represents reserving a quota unit before the final decision.

A client has one request left in its monthly quota. Two processes read the counter at the same time, both see an available slot, and both start working. Each request looks correct on its own, but together they sell the same unit twice. Checking used < limit before an ordinary counter increment does not establish who owns the last slot.

There is another failure mode: a request has already obtained its result, but a retry after a lost response charges the quota again. Or compensation runs twice and refunds a unit that another request has since consumed. The contract therefore needs to cover the whole life of a charge: admission, reservation, completion, and investigation of an unknown outcome.

Consider an independent exercise for one teaching Symfony application. InnoDB tables on MySQL 8.4 store the counter and reservation ledger; PHP accesses them through native PDO MySQL. Checks use separate connections and processes sharing a schema. This is a synthetic local model, not a measurement of a running API.

First decide what a unit pays for

In this exercise, one unit means successful local construction of an authorized response. A slot is occupied before the protected read and finalized after success. If the source authoritatively reports unsuccessful execution, the reservation can be refunded. Losing the response on the network after the work has completed does not cancel the charge.

This is an accounting policy choice. Another product might count every attempt, data volume, or the actual cost of an external call. The meaning of a unit must not change silently inside an error handler: otherwise the same request will have different prices depending on an accidental code path.

The model's used counter includes completed units and outstanding reservations. With a limit of 2 and an initial used = 1, one slot remains. Reserving it immediately raises the value to 2, even while the read is still running. Delaying the increment until the read ends would leave the slot available to another process.

Permissions come first. Verified identity, the required operation, and the permitted data scope must be established before reservation and before accessing content. Reading a credential or permission store is separate from the protected read counted by this exercise.

A period needs exact boundaries

Here a month is defined in UTC as a half-open interval: from the first instant of the current month, inclusive, to the first instant of the next month, exclusive. The new period starts exactly at the right boundary. This is a calendar month, not a duration of thirty days.

The time zone is part of the contract. If a product chooses another zone, every participant in the accounting must use that zone. The zone in which a client presents a date must not accidentally create a different monthly bucket for the same instant.

A reservation remembers the period of its first admission. If execution starts before a boundary and ends after it, confirmation or refund applies to the old month. A retry with the same identifier also finds the old reservation. Otherwise one logical request could be charged again against the new budget.

The last slot needs one transaction boundary

The example opens a short transaction through PDO, then performs a conditional increment in InnoDB:

UPDATE budgets
SET used = used + 1
WHERE tenant = ? AND principal = ? AND period = ?
  AND used < maximum;

One changed row means that the slot was taken. The reservation record is then inserted in the same transaction. If insertion fails, the adapter rolls back its own transaction, including the increment. Admission is returned to the caller only after that transaction commits successfully.

InnoDB coordinates concurrent changes through row locks. Lock waiting is bounded; native MySQL errors 1205 and 1213 are not converted into quota refusals. The adapter rolls back the transaction it owns and propagates the infrastructure error to the caller. The InnoDB error-handling documentation explains the distinction between statement and transaction errors. An infrastructure failure does not prove that the client has spent its limit.

The protected read happens after reservation, outside that short transaction. Holding a lock while a slow source responds would couple accounting throughput to the source's latency. The record already occupies the required slot, so the lock need not remain held throughout the read.

The conditional UPDATE is a locking write, not an ordinary snapshot read; the decision must not rely on an earlier unlocked SELECT. The separate counter example using SELECT ... FOR UPDATE explains explicit locking reads. This model's checks run on MySQL 8.4 with InnoDB at REPEATABLE READ isolation.

Request identity outlives a process

The ledger has a unique key consisting of three parts: tenant, authenticated client, and request key. Text identities use VARCHAR with the utf8mb4_0900_bin collation; foreign keys and CHECK constraints are enforced by MySQL. The period, request fingerprint, and reservation state are stored alongside it. Two sites can use the same key text while belonging to different accounting scopes.

A random string alone does not provide idempotency. Storage constraints and a retry rule are required. If a record already exists and its fingerprint matches, no new unit is occupied and the work is not executed again. If the key is the same but the operation differs, the request is rejected. The canonical representation used for the fingerprint must include every parameter that changes the operation's meaning.

In this exercise, the key stays unique throughout the retained ledger's lifetime, including month boundaries. Removing old records requires a separate limit on how long retries are accepted. Deleting a record while promising unlimited memory of past requests is impossible.

Accounting idempotency does not reconstruct the response body either. This exercise's ledger does not store the read result. A retry reports the existing state; returning the same response needs separate result storage and availability rules. Reading the source again “without charging” would introduce a different contract.

A refund must belong to a specific reservation

State Meaning Allowed next action
pending A unit is occupied; no final decision exists Confirm success or an established failure
committed Successful execution finalized the unit A retry returns this state without changing the counter
released An established failure refunded the unit A retry returns this state without another refund

A refund changes pending → released and decrements the original period's counter in one transaction. Confirmation changes pending → committed without adding another unit: that unit was already occupied earlier.

A late refund after committed does not reverse the charge. A repeated refund after released also changes nothing. This matters especially when another request has occupied the freed slot between the two attempts. A plain “decrement the counter if it is positive” could refund somebody else's unit.

That transition must be persisted alongside the counter. A flag in one PHP process's memory explains only that process's own history. After a restart or a call from another process, a shared record must reveal the decision already made.

An unknown outcome is not a failure

An exception can occur before execution, after execution, or while receiving acknowledgement. A general catch therefore must not refund quota automatically. In the example, only a separate type of established failure permits compensation; other cases require investigation of the outcome.

If a process disappears after reservation, its record stays pending. That reduces the available balance, but it does not invent a refund. The reservation's age alone cannot establish that the operation never ran. An authoritative source of the outcome is needed, such as the execution journal for the same logical request.

Even a refund error is ambiguous. The record may have been saved while its acknowledgement was lost. A prepared scenario models precisely that sequence: the transition completes, then a controlled failure hides the response from the caller. A subsequent read through a new connection must find the actual state. Before that read, neither “the refund did not happen” nor “everything completed” is justified.

The model provides a durable accounting record, but it does not automatically discover the truth about an external operation. Passing known_failure to the completion method is a trusted orchestration action after obtaining evidence. A client parameter or a timeout alone is not such evidence.

A nested transaction changes what “saved” means

An inner method can finish successfully while its caller can still roll back all of its records. In particular, releasing a MySQL savepoint neither commits the outer transaction nor prevents its later rollback.

The teaching adapter therefore requires a dedicated connection and refuses a caller that has already opened a transaction. It opens its own transaction through PDO only after that check and does not issue ROLLBACK on another owner's behalf. Outer-transaction and savepoint checks must establish that the adapter's refusal neither rolls back nor commits the caller's records.

This is not a universal prohibition on composed transactions. Another architecture can deliberately give transaction ownership to the caller. In that case, however, a returned “admission” cannot yet be described as a durably saved charge, and the order of external work must be coordinated with the actual commit.

Two connections must actually meet

The baseline scenario specifies a limit of 2, initial usage of 1, and requests A and B. Two separate processes create their own connections and wait for a shared signal. The observed outcome was one success, one quota refusal, final usage of 2, and exactly one protected read. Either process may win.

Another scenario holds the required row lock in an open transaction while a neighboring process attempts to reserve a unit. With a bounded wait, that process must receive native MySQL error 1205 before the lock is released, without a protected read. This distinguishes actual session overlap from two sequential calls using different connection objects.

The pair is supplemented by two processes replaying one key, a refund after somebody else's new reservation, a lost accounting acknowledgement, the month boundary, distinct tenants, and refusal before reading. The eventual result must explain more than the final number: which request gained permission to work, which state was persisted, and where uncertainty still needs a separate decision.

What the checks establish

The last-slot check ties one ok, one denied, and final used = 2 to one protected read and one audit row. The same-key race checks one ok and one replay, without a second protected read. Workers use their own native PDO connections sharing a schema and wait for a shared signal. The winning worker's name is not part of the contract.

In the held-lock scenario, event ordering matters: the child finishes its attempt with a native lock-wait error before the parent's COMMIT and performs no protected read. After commit, a fresh connection checks the budget. This checks a specific transaction overlap, not lock-wait performance or behavior under arbitrary load.

The checks cover authorization before accounting and reading, a single refund after established failure, late refund after success, terminal-state conflicts, unknown outcome, lost refund acknowledgement and fresh-connection readback, the UTC month boundary, cross-month replay, request fingerprints, tenant isolation, and transaction ownership. Running them requires MySQL 8.4 and the PDO MySQL extension. Database-dependent lab commands run through bash fixtures/mysql_labs/run.sh; App\Infrastructure\MysqlLab creates the guarded disposable database, and a separate migrator prepares its schema before business transactions. The runtime account performs DML and has no CREATE, ALTER, or DROP privileges. MySQL DDL can implicitly commit: this is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database.

The checks use network connections to MySQL but do not call external services. They do not establish HTTP authentication integration, power-loss or crash recovery, or distributed exactly-once behavior. Trusted authorization and an established failure remain orchestration boundaries: a generic timeout does not authorize a refund.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/MonthlyQuota
  1. API Permission to act and permission to access data: two checks for one API request
  2. Databases Handler idempotency: repeat the task without duplicating its result
  3. Platform Engineering Timeout after an external request: when the outcome is unknown
  4. Knowledge & AI AI request cost: estimates, actual usage and the budget boundary