SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Rate Limiting
  • Authentication vs Authorization
  • Session vs Token Based Auth
  • JWT
  • OAuth / OAuth2
  • Single Sign-On (SSO)
  • API Keys
  • OpenID Connect (OIDC)
  • CSRF
  • Input Validation
  • mTLS and Request Signing (HMAC)
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Security

API Keys

A simple secret that tells an API which app is calling, and how to handle it safely.

⏱ 11 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An API key is a long, random string that a program sends with each request, to tell the API which app is calling. It is the simplest way to identify callers, track their use and set limits for each one.

  • A key identifies an application, not a person. It says "this is the weather widget", not "this is Priya".
  • Send it in a header, never in the URL. Store only a hash of it on the server.
  • A key is a password for a program. If it leaks, anyone can use it, so give it limited scope, a rate limit and a way to rotate it.

02Concept: What is it?

When a company opens an API to other developers, it needs to know who is calling. The developer signs up, and the company creates a key for their app. The app then adds the key to every request, usually as a header such as X-API-Key or Authorization.

Using a key (illustrative)
GET /v1/forecast?city=Pune
Host: api.example.com
X-API-Key: sk_live_9fA3...  (a long random value)

On the server, the key is looked up. If it is valid, the server knows who the caller is, what it may do (its scope) and how much it may do (its rate limit and quota). That is enough for many machine-to-machine cases.

What the server does with a key
πŸ“±Appsends the key
→↓header
πŸšͺGateway / APIhash the key, look it up
→↓found
🧾Key recordowner, scope, limit, status
The server never keeps the key itself, only a fingerprint of it, so a stolen table is not a list of working keys.
🧠Not a user login
An API key says which app. It does not say which user approved anything. If you need to act on behalf of a user, use OAuth2 or OpenID Connect.

03Real-Life Example

🍡The Delivery Company Badge
A delivery company gives each supplier a badge with a number. The guard at the warehouse gate scans the badge: it shows which supplier it is, which doors they may use (loading dock only) and how many trucks they may bring each day. The guard does not know the driver's name, and anyone who holds the badge gets in. So the company keeps a list of badge numbers (not the badges themselves), can cancel one badge at once, and issues a new badge before the old one expires.
Supplier badge
API key
A badge number the guard scans
A key sent in a request header
Which supplier it belongs to
The app or customer that owns the key
Only the loading dock
Scope: the key may do only some things
Maximum trucks per day
Per-key rate limit and quota
Anyone with the badge gets in
Anyone who has the key can use it
Cancel the badge at once
Revoke the key
New badge before the old one ends
Rotation with an overlap
The life of a key
πŸ†•Createshow it once
→↓
πŸ”‘Usein a header
→↓
πŸ”„Rotateold and new overlap
→↓
πŸ›‘Revokewhen leaked or unused

04Why Do We Need It?

πŸͺͺKnow the caller
Every request is tied to an app, so you can support, bill and block them one by one.
πŸ“ŠPer-caller limits
A rate limit and quota for each key stop one customer from using everything.
🧭Usage and billing
Count calls per key for dashboards, plans and invoices.
🧰Simple to adopt
One header is easy for any developer in any language. No login pages or redirects.
πŸ”’A first gate
Anonymous traffic is turned away before it reaches expensive code.
🧱Revoke one, not all
If one customer leaks a key, you cancel only that key.
API keys give a fast, simple way to say who is calling. Keep them narrow, limited and easy to replace, because anyone who holds one can use it.

05Where Do We Use It?

🌦️Public data APIs
Weather, maps, exchange rates: a key tracks use and enforces a free quota.
πŸ”ŒServer-to-server calls
Your back end calls a partner’s API with a key kept in a secure place.
πŸ§ͺDeveloper sandboxes
Test keys and live keys let developers try an API safely before going live.
πŸšͺAPI gateways
The gateway checks the key, applies the plan’s limits and then forwards the call.
πŸ“ˆAnalytics and monitoring
Dashboards break traffic and errors down by key.
πŸ€–Automation and scripts
A script or a CI job needs a simple credential that no human types in.

06Types / Parts / How It Works

Where to send the key

PlaceExampleVerdict
Request headerX-API-Key: ... or Authorization: Bearer ...Best. Headers are not stored in browser history and are usually kept out of access logs.
Query string/forecast?api_key=...Avoid. The key ends up in logs, browser history, bookmarks and Referer headers.
Request bodyA field inside a JSON bodyPossible for POST calls, but unusual, and the key is not available to a gateway before the body is parsed.
CookieCookie: key=...Only for browser sessions. That is a session, not an API key.

API keys compared with other credentials

CredentialIdentifiesLifetimeBest for
API keyAn app or customer accountLong, until rotated or revokedSimple identification, quotas, server-to-server calls
OAuth2 access tokenAn app acting for a user, with approved scopesShort (minutes to hours)Acting on behalf of users
JWTA signed set of claims (user, app, expiry)ShortPassing identity between services
mTLS client certificateA machine, proven by a certificateMonthsStrong service-to-service identity
Signed requests (HMAC)A caller, proven by a signature on each requestPer requestProving the message was not changed

A good key design

Parts of a key and its record
What the customer sees once
πŸ”‘sk_live_ab12prefix: type + id
🎲long random partfrom a secure generator
What the server stores
#️⃣hash of the keynot the key
🏷️prefix + owner
🎯scopes
⏱️limit + expiry
🚦status
Shown to the owner Stored Controls
The prefix helps people find a key in a dashboard or a leak report without revealing the secret part.
VisualizerHow a leaked key does damage: and what shrinks itPick a way the key leaks, then switch scope, rate limit, hashing and a short lifetime on and off. Drag the notice time to see how long an attacker has.
How does the key leak?
Key limited to read-only scope?
Per-key rate limit?
Server stores only a hash?
Key lifetime (rotation)
Requests an attacker could send with one leaked key, compared with no protection at all
Your setup33,600,000 requests
No scope, no limit, never rotated33,600,000 requests
Keys exposed
1
the leaked key
Exposure window
14 days
shorter of notice time and half the life
Requests per key
33,600,000
illustrative
Worst thing they can do
Read, write, delete
set by the key scope
A key pushed to a public repository can be found and used very fast, because bots scan for key formats. Deleting the file does not remove it from the history, so the only real fix is to revoke the key. With these settings an attacker could read, write, delete for about 14 days, at up to 100,000 requests per hour.

Illustrative numbers only: 100,000 requests per hour without a limit, 1,000 with one, 500 customers. On average a key leaks half way through its life, so a shorter life cuts the exposure window. The model does not cover attackers who copy a key and wait.

07How to Use It / Steps / Implementation

Running an API key system well

  1. 1
    Generate keys from a secure random source
    Use a cryptographically secure generator and make the key long. Never build keys from a user id, a date or a counter that someone could guess.
  2. 2
    Show the key once
    Display the full key only at creation. After that, the dashboard shows the prefix and the last few characters.
  3. 3
    Store only a hash
    Keep a hash of the key and look keys up by that hash (or by the prefix, then compare). Then a stolen database cannot be used as a list of keys. Because keys are long and random, a fast hash is acceptable here. Passwords are different and need a slow hash.
  4. 4
    Send keys in a header
    Document the header name. Reject keys in the URL, or at least warn, and keep them out of your own logs.
  5. 5
    Give every key scope and limits
    Make the least-powerful key the easy default. Add a per-key rate limit and quota, and an optional expiry date.
  6. 6
    Make rotation painless
    Let a customer have two active keys at once. They create the new one, switch over, then delete the old one with no downtime.
  7. 7
    Detect and revoke
    Watch for odd use (new countries, sudden spikes). Let customers and your team revoke a key at once. Register your key format with secret-scanning services, so that leaks in public repositories are noticed.
πŸ’‘Keys belong on servers
Call APIs that need a key from your back end. A key placed in a web page or a mobile app can be read by anyone, so treat it as public and give it tiny scope, or use a user login instead.
⚠️A key is not enough for sensitive actions
For payments or personal data, add more: OAuth2 for user consent, mTLS or signed requests for strong machine identity, and IP allow-lists where it makes sense.

08Key Terms to Know

TermMeaning in easy words
API keyA long random string that identifies the calling app to an API
ScopeThe list of things a key is allowed to do (for example, read only)
Rate limit / quotaHow many calls a key may make per second or per month
Key prefixA short, non-secret start of the key that helps people recognise it
Hashing a keyStoring a one-way fingerprint of the key, not the key
RotationReplacing a key with a new one, ideally with a period when both work
RevocationCancelling a key so it stops working at once
Blast radiusHow much damage is possible if one credential leaks
Least privilegeGive a key only the access it needs, and no more
Secret scanningTools that search code and repositories for leaked keys
Test key / live keyA key for a sandbox, and one for real data

09Pros, Cons and Trade-offs

βœ… Pros
  • Very simple for developers to use
  • Easy to track, limit and bill per caller
  • Cheap for the server to check
  • Can be revoked one at a time
  • Works for any language and client
⚠️ Cons
  • Anyone with the key can use it (a bearer secret)
  • Identifies an app, not a user
  • Long lived by default, so leaks last
  • Easy to leak into code, logs and URLs
  • No built-in proof that a request was not changed

Trade-offs

ChoiceWe gainWe lose
Long-lived keysNothing to renew, simple for clientsA leak is dangerous for a long time
Short-lived keys / tokensA smaller window for attackersClients must refresh, and need more code
Broad scopeOne key does everythingA leak exposes everything
Narrow scopeA leak does little harmMore keys to create and manage
Hash on the serverA stolen database is not a list of working keysYou can never show a key again, so lost keys must be replaced
Strict per-key limitsProtects the service and other customersLegitimate bursts get refused

10Common Problems and Mistakes

Common mistakes

  1. Keys in the URL. They end up in browser history, proxies and logs, and are passed on in Referer headers.
  2. Keys in code or git. Bots scan public repositories for key formats within minutes. Deleting the file does not remove it from the history. Revoke the key.
  3. Keys in a mobile app or web page. Anyone can pull them out. Put the call behind your own server.
  4. Storing keys as they are. A database leak then hands over every customer's key.
  5. One key for everything. No scope and no limit means one leak is a disaster.
  6. No rotation plan. If replacing a key needs downtime, nobody will do it, and old keys live for years.
  7. Using a key as user identity. A key cannot show that a particular person agreed to something.

Things to watch

πŸͺ΅Keys in logs
Check that request logs, error reports and traces never record the key header.
🧟Forgotten keys
Unused keys are free access for attackers. Show β€œlast used” and expire idle keys.
πŸ‘₯Shared keys
When five teams share one key, nobody can tell who made a call, and nobody dares to rotate it.
πŸ”ŽTiming attacks
Compare hashes with a constant-time comparison, so response time does not reveal how much of a guess was right.

11Real-World Examples

πŸ—ΊοΈMaps and data APIs
Many provide a free tier with a key, and ask you to restrict the key to certain sites, apps or IP addresses.
πŸ’³Payment providers
They issue test and live keys, often with a recognisable prefix, and offer restricted keys with narrow permissions.
☁️Cloud providers
They push you towards short-lived, role-based credentials instead of long-lived keys, where they can.
πŸ™Code hosting platforms
They scan public repositories for known key formats and tell the issuer when a key leaks.
πŸšͺAPI gateways
Gateways manage keys, plans and limits so that every service does not have to.
πŸ§ͺCI systems
Pipelines keep keys in a secrets store and inject them only while a job runs.
πŸ“Note
Prefixes, restrictions and rotation features differ between providers. Read the documentation of the one you use.
Mini case: a key leaks into a public repository
πŸ™Key pushedto a public repo
→↓scanner finds it
πŸ””Issuer alertedkey revoked
→↓rotate
πŸ†•New keynarrow scope, short life
Leak Detect Recover
Each protection shortens or shrinks the damage.

12Related Topics to Read Next

Authentication vs Authorization→

A key proves which app, and scopes decide what it may do.

OAuth / OAuth2β†’

The better choice when an app acts on behalf of a user.

JWT→

A short-lived signed credential that carries claims.

Rate Limiting→

Limits are usually applied per key.

Secrets Management→

Where keys should be kept on the caller’s side.

mTLS and Request Signing (HMAC)β†’

Stronger ways to prove who is calling.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a long random string that tells an API which app is calling.
  • βœ”Send: in a header, never in the URL.
  • βœ”Store: only a hash. Show the key once. Compare in constant time.
  • βœ”Limit: narrow scope, per-key rate limit, quota and expiry.
  • βœ”Rotate: two keys active at once, then revoke the old one.
  • βœ”Never: in git, logs, URLs, web pages or mobile apps (or treat as public if you must).
  • βœ”Not a user: for user consent use OAuth2 or OpenID Connect.
  • βœ”One line: β€œA key is a password for a program: keep it narrow, limited, hashed and replaceable.”
← Previous
Single Sign-On (SSO)
Next β†’
OpenID Connect (OIDC)