← Building blocks

Identify API clients

Security & abusefundamental

Machine clients need an identity to rate limit and bill.

Say it like this

Machine clients need a stable identity I can rate limit, scope and revoke, so I issue random keys, store only a hash, and look the hash up on every request.

Basic solution

Issue random API keys, store only their hash, and look up on each request; scope keys to permissions.

hashed API keysHMAC request signingkey rotation

Hash on the way in, owner id on the way through

The plaintext key exists only on the client. The gateway hashes it, resolves the owner and scopes from a cached table, and forwards the identity downstream where limits, metering and permissions apply.

How it works

  1. The developer creates a key in a dashboard. The server generates 32 random bytes, encodes them as base62 (about 43 characters), prepends a recognisable prefix such as sk_live_, and shows the full key exactly once. After that moment the plaintext exists only wherever the developer saved it.
  2. The server stores SHA-256(key) together with the owner, the scopes (what the key may do), created_at, last_used_at and a status. The plaintext key is never written to the database, logs or backups.
  3. On each request the client sends the key in a header. The gateway hashes it with the same SHA-256, looks the hash up in a cache that fronts the key table, checks that the status is active and the scopes cover the endpoint, and attaches the owner id to the request before forwarding it.
  4. That owner id drives everything downstream: rate limits are counted per owner, usage is metered per owner for billing, and services check the key's scopes against the action (this key may create links but not delete them).
  5. Rotation never requires downtime: the owner creates a second key, moves clients across to it, and revokes the first. Both keys are valid during the overlap, so a client that has not switched yet keeps working.

Why a hash and not encryption

  • The server only ever needs to recognise a key, never to recover its plaintext, so a one-way hash is enough. If the key table leaks, the hashes cannot be turned back into usable keys.

Worked example

URL shortener creation API

  • 20,000 developer accounts, 2 keys each on average: 40,000 rows of 200 bytes, 8 MB. The whole table fits in memory; a Redis cache keyed by hash answers lookups in 0.3 ms.
  • Key size: 32 random bytes is 256 bits of entropy. Guessing is impossible; the prefix sk_live_ lets secret scanners find leaked keys in public repositories and lets you revoke automatically.
  • Hashing cost: SHA-256 of 50 bytes is about 1 microsecond. At 40 creates/s (or 40K/s at a burst) it is invisible. Do not use bcrypt here: keys are high-entropy, so a slow hash buys nothing and costs 100 ms per request.
  • Rate limit per key: 100 creates/min for the free tier, 10,000/min for paid. The limiter key is the owner id, so a customer with 3 API keys shares one budget.
  • Rotation window: 7 days of overlap by default; last_used_at tells the dashboard when the old key has gone quiet so the owner can revoke it with confidence.

Variants and when each wins

Opaque random key looked up by hash

  • A random string with no meaning inside it, resolved to an owner by hashing and looking it up. It wins as the default for public APIs because it is simple and revocable instantly; it costs one cache or table lookup per request.

Signed self-describing key

  • The key is a signed blob that carries the owner and scopes, verified locally with no lookup, like a JWT that never expires. It wins on request-path speed; revocation needs a deny list and scopes cannot change without issuing a new key.

HMAC request signing

  • The client signs each request (method, path, body hash, timestamp) with a secret that is never sent over the wire. It wins when tampering and replay must be prevented even over a compromised channel, as AWS SigV4 does; it is harder for clients to implement.

Mutual TLS

  • Each client presents a certificate, and identity comes from the TLS layer. It wins for service-to-service calls inside a mesh because no secret travels in headers; it is heavy to operate because certificates must be issued, rotated and revoked.

Recommendation: opaque hashed keys with a prefix for public APIs; HMAC signing when payload integrity matters (payments, webhooks); mTLS inside the network.

Failure modes

Key leaked through a URL

  • Keys appear in access logs, browser history and referrer headers. It happens because clients were allowed to pass the key as ?api_key= in the query string. Accept keys only in a header and reject query-string keys with a clear error message.

Plaintext keys in the database

  • A database dump lets anyone impersonate every customer. It happens because the key itself was stored rather than its hash. Store the hash, show the key once at creation, and provide rotation so a leaked key can be replaced.

No rotation path

  • A leaked key cannot be replaced without an outage. It happens because each account has exactly one key, so revoking it breaks the client until a new one is configured. Allow several active keys per owner with an overlap period, and expose last_used_at so the owner knows when the old key has gone quiet.

Scopes missing

  • A key issued for reading analytics can delete links. It happens because keys are all-or-nothing. Store scopes on the key row, have each service check them against the action, and default new keys to the least privilege that works.

Lookup store on the critical path

  • Every API call fails while the key cache is down. It happens because the gateway has no fallback when the lookup fails. Cache with a long TTL, serve the last known status while the store is unreachable, and consider replicating the small key table into each gateway.

Interviewer follow-ups

Answer out loud before you open each one.

Why not use a JWT instead of an API key?

A JWT expires and must be refreshed, which suits interactive users but not a cron job with a key in config. API keys are long-lived by design and revoked by deleting a row. Many APIs offer both: keys for scripts, OAuth tokens for apps acting on behalf of a user.

How do you handle a key that leaks on GitHub?

Prefixed keys let scanning partners detect them; the webhook revokes the key automatically and emails the owner with a new one. Internally, last_used_at and source IP history show whether it was used before revocation. The overlap-rotation design means the owner can recover without downtime.

Where should the key check happen, gateway or service?

At the gateway, once, with the resolved owner id and scopes forwarded as trusted headers or an internal token. Services then enforce scopes against the resource. The gateway must strip any client-supplied copies of those headers so a caller cannot impersonate the gateway.

How do you meter usage per key for billing?

The gateway emits one event per request with owner id, key id, endpoint and status to a stream; a consumer aggregates per minute into a usage table. Billing reads the aggregate, never the raw stream. Counting synchronously in the request path would add a write per call and a hot counter row.

Connections

Pairs with
Authenticate, then authorise · Limit requests per client · One front door for many services · Protect data and secrets · Log so you can query
Used in
URL Shortener (TinyURL / bit.ly) · Distributed Rate Limiter

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon API GatewayAPI gatewayAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon ElastiCacheKey cache, Rate limiterMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon DynamoDBapi_key tableFirestore, BigtableCosmos DBScyllaDB, Apache Cassandra
Amazon EC2 Auto ScalingURL serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon Kinesis Data StreamsUsage streamPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar