How-To Guide

How to Implement Request Quotas per API Key

Meter usage per API key over a billing period, enforce it beyond the short-term rate limit, and tell clients how much remains.

On this page

  1. Introduction
  2. Quotas Versus Rate Limits
  3. Counting Usage Per Key
  4. Windows and Rolling Usage
  5. Enforcing and Returning the Remaining
  6. Handling Overages
  7. Quotas, Time Zones and Resets
  8. Conclusion

Introduction

A rate limit and a quota sound similar and solve different problems. A rate limit bounds how fast a client may send, controlling burstiness and protecting the service in the moment. A quota bounds how much a client may send over a longer period, such as a month, and is the basis for a plan or a bill. A client can be well within its rate limit and still exhaust its quota, or have quota left and still be throttled for bursting. This article covers counting usage per key, enforcing the quota at the edge, returning the remaining allowance, and handling overages without surprising the client.

Quotas Versus Rate Limits

A rate limit is about rate: requests per second or per minute, enforced with a short window, and its purpose is to keep the service healthy under concurrency. A quota is about volume: requests per day or per month, enforced over a long period, and its purpose is to make consumption predictable and billable. They operate on different timescales and are both needed.

Confusing them produces two bugs: a client that hits the rate limit but has plenty of quota is throttled without understanding why, and a client that quietly exhausts its monthly quota is blocked until the period resets. Return both signals so the client can tell which limit it hit and what to do.

Counting Usage Per Key

The usage counter is keyed by the API key and the period. A durable counter that survives restarts is needed, because the quota spans a month and an in-memory counter would reset on every deploy. Increment the counter on each request and store the period boundary with it, so a new period naturally starts a new count.

Count at the point the request is accepted, not after it completes, so a rejected request does not consume quota unless you intend it to. Decide explicitly whether failed requests count; for most APIs only accepted requests consume quota, and the counter is incremented once per accepted request.

CREATE TABLE api_usage (
  api_key      text NOT NULL,
  period_start date NOT NULL,          -- e.g. the first day of the month
  used         bigint NOT NULL DEFAULT 0,
  PRIMARY KEY (api_key, period_start)
);

-- Atomically consume one unit and return the new total, or refuse if over.
-- Returns the used count if consumed, or NULL if the quota is exhausted.
UPDATE api_usage
SET used = used + 1
WHERE api_key = $1 AND period_start = $2
  AND used < (SELECT quota FROM api_keys WHERE key = $1)
RETURNING used;

Windows and Rolling Usage

A fixed monthly period is simple and predictable but allows the same burst-at-the-boundary problem as a fixed rate window: a client can use its whole quota on the last day of one month and the first day of the next. A rolling window over the last thirty days smooths this but is harder to bill and harder to explain.

Choose based on what the quota is for. A plan with a monthly allowance and a monthly bill usually wants a fixed calendar period, and the boundary burst is acceptable. A quota meant to smooth load wants a rolling window. State the choice plainly, because clients build retry and batching logic around it.

Enforcing and Returning the Remaining

The quota check belongs at the edge, before the expensive work, alongside the rate limit. When the request is accepted, atomically increment and read the new total, and return the remaining allowance in a response header so the client can pace itself. When the quota is exhausted, reject with a status that says why and a time when it resets, so the client does not retry blindly.

async function enforceQuota(db, apiKey) {
  const periodStart = firstOfMonth(new Date());
  const { rows } = await db.query(
    `UPDATE api_usage
        SET used = used + 1
      WHERE api_key = $1 AND period_start = $2
        AND used < (SELECT quota FROM api_keys WHERE key = $1)
      RETURNING used`,
    [apiKey, periodStart],
  );
  if (rows.length === 0) {
    const quota = await getQuota(db, apiKey);
    return {
      allowed: false,
      remaining: 0,
      resetAt: firstOfNextMonth(new Date()),
      limit: quota,
    };
  }
  const used = rows[0].used;
  return { allowed: true, used, remaining: (await getQuota(db, apiKey)) - used };
}

// Headers tell the client exactly where it stands.
//   X-Quota-Limit: 100000
//   X-Quota-Remaining: 432
//   X-Quota-Reset: 2026-11-01T00:00:00Z

Handling Overages

Decide the overage policy before the first client hits it. The choices are hard stop, refuse until the period resets; soft cap, allow with a warning and bill the excess; and burst allowance, a small overage permitted before the hard stop. Each is a product decision, and the API must implement it consistently rather than failing unpredictably.

Warn before the cap: return the remaining allowance on every response so a well-behaved client can slow down, and send a notification when the remaining crosses a threshold such as eighty percent. A client blocked at a hundred percent without warning is a support ticket; one warned at eighty percent can act.

Quotas, Time Zones and Resets

A period boundary needs a time zone. A monthly quota that resets at midnight UTC is predictable; one that resets at the server’s local midnight moves with the deployment. Pick UTC or a documented zone and keep it fixed, because clients compute their next reset from it.

Store the period boundary with each usage row rather than computing it from the current date, so a stored count is always attributed to the period it belongs to. When the period rolls over, the first request of the new period creates a new row with zero used, and the old row remains for billing and history.

Conclusion

A quota bounds volume over a long period and complements the short-term rate limit. Count usage per key and period in durable storage, increment atomically only for accepted requests, enforce at the edge, and return the remaining allowance and the reset time on every response so the client can pace itself. Choose a fixed or rolling window deliberately, pick a documented reset time zone, and warn at a threshold before the hard stop. Then a client never hits a quota it did not see coming.

Sources: Stripe: usage-based billing, Google Cloud: quotas, IETF draft: RateLimit header fields.

FAQ

How is a quota different from a rate limit?
A rate limit bounds how fast a client sends over a short window and protects the service in the moment. A quota bounds how much a client sends over a long period and is the basis for a plan or a bill. A client can be within its rate limit and still exhaust its quota.
Should failed requests consume quota?
Usually not. Count only accepted requests, and increment the counter once per accepted request at the point of acceptance, so a rejected or failed request does not consume allowance the client did not use.

Related Examples