API & Automation·7 min read·

API Key Rotation and Revocation Workflows

Design API key rotation and revocation workflows so a leaked key becomes a small, contained event instead of a full platform emergency.

NB

Netbay Infrastructure Team

Netbay Engineering

On this page

The humble API key is a shared secret, and every shared secret leaks eventually. What separates robust platforms from fragile ones is not avoiding leaks — it is having rotation and revocation workflows that make a leak a small contained event instead of a full emergency. This post lays out those workflows.

The lifecycle an API key should have

A key should pass through states you can see and control: **issued**, **active**, **expiring**, **revoked**. The moment you treat rotation as a process rather than a manual scramble, security incidents get dramatically cheaper to resolve. The pieces are: a generated key with an embedded identifier, a stored hash (never the raw key), an issue timestamp, a created-by agent, and an expiry.

Scope the key to the narrowest permissions it needs and give it a sensible lifetime. Short-lived keys reduce the unavoidable window, but for machine credentials you must balance renewal effort. Many teams pair a monthly rotation with per-key scopes.

Store each key as a hash rather than in plaintext so that a read of your credentials table is not itself a full compromise. The raw key should exist in exactly two places: first on your issue screen, where the customer copies it once, and then in the environment they deploy into. Tying keys to a clear owner and a contact also matters — when one key needs urgent rotation, you want to know which team runs the dependent service and who to notify, not to page a generic on-call rotation that discovers the dependency only by breaking it.

issued active expiring revoked audit each state transition who, when, which key id

Rotation without downtime

Rotation must not break currently-deployed clients the instant a key lands or disappears. The standard trick is **dual-key rotation**: issue the new key, let it become active alongside the old one for a grace window, then retire the old. The client swap is asynchronous and graceful.

Concretely, store each key separately with its own identifier. The server accepts requests signed by any active key and flags which key actually authenticated the request. Then stage the change: create key B while A is still valid, move clients to B, wait out the overlap, then revoke A.

A rotation state machine, in Go

go
type KeyRecord struct {
    ID        string
    Hash      string
    Status    string // active, retiring, revoked
    ExpiresAt int64
}

// accept if any provided key is active; report which one
func (s *KeyService) Check(key string) (string, error) {
    rec := s.byHash(hash(key))
    if rec == nil || rec.Status == "revoked" {
        return "", errors.New("invalid key")
    }
    if rec.Status == "retiring" {
        return rec.ID, nil // valid during grace window
    }
    return rec.ID, nil
}

Revoking immediately on breach

javascript
async function revokeKey(db, keyId, reason) {
  const k = await db.get("keys", keyId);
  if (!k) return { ok: false };
  await db.put("keys", keyId, {
    ...k,
    status: "revoked",
    revokedAt: Date.now(),
    reason,
  });
  // drop cached key immediately
  await cache.del("key:" + keyId);
  return { ok: true };
}

When you suspect a breach, revoke at the first sign — do not wait for confirmation, because every request a compromised key serves is a request you lose. If a cache holds validation results, invalidate them on revocation so the change is instant, not eventual.

The deeper your automation goes, the less this workflow depends on human memory. A scheduled job can detect keys approaching their expiry, file the rotation ticket, and — once the new key is confirmed working — retire the old one, all without an engineer keeping a mental calendar. The goal is that rotation happens quietly and repeatedly in the background, so that the manual, stressful version is reserved for genuine emergencies rather than routine hygiene.

Make rotation observable

  • Log every issuance, activation, and revocation with the acting agent and timestamp.
  • Alert on a key authenticating a surprising share of traffic or from a new network.
  • Send an expiry-notice a week ahead so humans are not caught off guard.

Takeaway

Treat every API key as already on a clock: scoped, hashed at rest, dual-rotated without downtime, and one action away from instant revocation. Good workflows turn a key leak from an outage into a routine fix. Build and exercise these paths against your API on a Netbay VPS at netbayhosts.in.

Keep reading

Follow along on a real VPS

Deploy Linux in under 60 seconds

These guides are written against Ubuntu, Debian, and RHEL-family images — the same ones on NetBay.

Deploy an instance