How do I rotate and revoke keys in Unkey without breaking existing customers?
API Access Management

How do I rotate and revoke keys in Unkey without breaking existing customers?

10 min read

Key rotation and revocation are essential for keeping your APIs secure—but if you handle them carelessly, you risk breaking live integrations and frustrating existing customers. With Unkey, you can rotate and revoke keys in a controlled, staged way that keeps your API secure while maintaining backward compatibility for consumers.

This guide walks through practical strategies, patterns, and workflows for rotating and revoking keys in Unkey without interrupting existing customers.


Why key rotation and revocation matter

Before diving into Unkey-specific workflows, it helps to clarify the goals:

  • Security: Reduce blast radius if a key is leaked or compromised.
  • Compliance: Many standards expect regular key rotation.
  • Operational safety: Avoid downtime and broken integrations during key changes.
  • Customer experience: Give customers time and tools to update their credentials smoothly.

Unkey’s API-first design, rate limiting, and automatic key expiration make it easier to build a rotation strategy that’s both secure and user-friendly.


Core concepts to use in Unkey

When designing your rotation and revocation flow, plan around these capabilities:

  • API-first / UI-first
    You can manage keys via Unkey’s dashboard for non-technical users, or fully automate via the REST API / SDK (@unkey/api for TypeScript, and other languages).

  • Global, fast propagation
    Role and permission changes propagate globally in seconds. This means revoking or degrading a key’s permissions takes effect quickly worldwide.

  • Rate limiting & usage limits per key
    You can gradually degrade old keys using stricter rate limits or usage caps, safely nudging customers to migrate to new keys.

  • Automatic key expiration
    You can create keys with built-in expiry, reducing long-term risk and enabling scheduled, predictable rotation.

These primitives let you move from “panic key revocation” to “planned, gradual rotation.”


The safe key rotation pattern in Unkey

The safest way to rotate keys without breaking existing customers is to use a dual-key (or multi-key) window and a deprecation schedule:

  1. Create a new key
  2. Distribute the new key to the customer
  3. Allow both old and new keys to coexist for a defined migration window
  4. Monitor usage to confirm successful migration
  5. Tighten limits or permissions on the old key
  6. Revoke the old key once it’s no longer in use

Below is a step-by-step breakdown of how to implement this with Unkey.


Step 1: Make key rotation an explicit part of your API design

Before you touch Unkey, ensure your own API and customer contracts support rotation:

  • Expose a “Manage API keys” area in your product
    Use Unkey’s dashboard or API to let customers:

    • Create new keys
    • View usage
    • Revoke their own keys
  • Document rotation expectations
    In your docs and onboarding:

    • Encourage customers to treat keys as secrets that can be rotated
    • Define default rotation intervals (e.g., every 90 days)
    • Explain how to switch keys safely
  • Support multiple active keys per customer
    Design your system so each customer can hold multiple valid keys simultaneously (e.g., for blue–green deployments).


Step 2: Create and verify keys via Unkey’s API

You can manage keys programmatically with the Unkey SDK, which makes it simple to rotate keys in CI/CD pipelines or internal tooling.

Example verification flow with TypeScript:

import { Unkey } from "@unkey/api";

const unkey = new Unkey({
  rootKey: process.env["UNKEY_ROOT_KEY"] ?? "",
});

export async function verifyIncomingKey(apiKey: string) {
  const result = await unkey.keys.verifyKey({ key: apiKey });

  // handle network errors
  if (!result || "error" in result) {
    // Implement your own error handling / fallback
    throw new Error("Unable to verify key with Unkey");
  }

  if (!result.valid) {
    // Reject unauthorized request
    throw new Error("Unauthorized");
  }

  // Proceed with authorized request
  return result;
}

In a rotation context, your backend shouldn’t need to change; it just calls verifyKey for whatever key the client presents. Rotation happens by issuing new keys and retiring old ones.


Step 3: Add a dual-key migration window

To rotate keys without breaking existing customers, always offer an overlap period where both old and new keys are valid.

Recommended workflow

  1. Issue the new key

    • Use Unkey’s API or dashboard to create a new key.
    • Optional: set an explicit expiration date so you know when it will need rotation again.
  2. Deliver the new key securely

    • Show it once in your product’s dashboard.
    • Never log or email keys in plaintext.
    • Encourage customers to update staging first, then production.
  3. Keep the old key active

    • Do not revoke the old key immediately.
    • Mark it internally as “deprecated” with a target sunset date.
  4. Communicate the migration window

    • Notify customers with:
      • The old key identifier (not the secret)
      • The new key identifier
      • A clear cutoff date (e.g., “This key will stop working in 30 days.”)
  5. Monitor usage

    • Track:
      • How many calls are still made with the old key
      • Which customers are still using it close to the deadline

This dual-key window is your primary safety net—customers can switch over at their own pace within a controlled period.


Step 4: Use rate limiting and usage limits on old keys

During the migration window, you can leverage Unkey’s rate limiting and usage limits per key to gradually reduce reliance on the old key without causing a hard break.

Strategies to consider

  • Soft degradation for old keys

    • Apply a stricter rate limit to the old key.
    • Keep the new key more generous.
    • Communicate the change so customers have incentive to switch.
  • Usage-based migration nudges

    • For old keys, set a temporary usage cap that is sufficient for normal operations but forces customers who are aggressively using the API to rotate.
    • For new keys, offer the full intended quota.
  • Tiered deadlines

    • High-value or critical customers might get:
      • More time
      • A higher temporary rate limit
    • This can be implemented by assigning different roles or permissions in Unkey and adjusting their rate limits accordingly.

This controlled degradation means even if customers delay, you minimize risk and gradually push them to the new key without a sudden outage.


Step 5: Use role-based access control for safe permission changes

Sometimes you don’t just want to rotate a key; you also want to change what a key can do (e.g., remove sensitive permissions after a leak).

Unkey’s role-based access control (RBAC) is a better tool than immediate revocation in many cases:

  • Attach roles or granular permissions to keys

    • Example roles: read-only, read-write, admin.
    • Permissions update globally in seconds.
  • Downgrade, then revoke

    • Phase 1: Remove high-risk permissions on the old key (e.g., write or admin).
    • Phase 2: Encourage migration to the new key with correct roles.
    • Phase 3: Fully revoke the old key once idle.

This approach lets you mitigate risk quickly while still giving customers time to update their configurations.


Step 6: Revoke keys once they’re truly unused

At the end of the migration window, you should revoke old keys that are no longer used.

Before revocation

  • Confirm via logs or Unkey usage data that:
    • The old key’s traffic has dropped to zero, or
    • Remaining traffic is from low-risk contexts and you’ve communicated clearly.

Revocation options

You can revoke a key by:

  • Using the Unkey dashboard to disable or delete the key.
  • Calling the appropriate Unkey API endpoint (depending on your key management setup).

Once revoked:

  • All calls with that key will fail verification.
  • Your backend should treat them as unauthorized and return clear error messages (e.g., HTTP 401 with a help link explaining how to generate a new key).

Communicate clearly

When revoking a key, make sure customers see:

  • A readable error: “API key revoked or expired”
  • A path to resolution: link to “Manage API keys” in your app
  • A support contact for urgent cases

Using automatic key expiration to avoid “forever keys”

Unkey’s automatic key expiration is one of the best tools for preventing long-lived, forgotten keys from becoming a security liability.

Best practices

  • Set default lifetimes on keys

    • Example: 90 days for production keys, 30 days for test keys.
    • Communicate this in your docs and UI.
  • Remind customers ahead of expiration

    • Use your own app’s notifications or email to warn:
      • 14 days before expiry
      • 7 days before expiry
      • 24 hours before expiry
  • Encourage seamless regeneration

    • Provide a “Rotate key” or “Generate replacement key” button that:
      • Creates a new key
      • Sets a short dual-key overlap
      • Automatically revokes the old key after a safe window

By combining automatic expiration with a dual-key strategy, you normalize rotation as a regular, expected part of using your API.


Handling emergency rotation and revocation (e.g., key leak)

Sometimes you don’t have the luxury of a long migration window—if a key is publicly exposed, you must act quickly.

Here’s how to respond using Unkey without unnecessarily breaking unaffected customers:

  1. Identify the compromised key

    • Use your own logs or Unkey data to find the exact key.
    • Confirm scope: Is it a single customer key or a root/admin key?
  2. Reduce permissions immediately

    • Use RBAC to strip sensitive permissions (e.g., write or admin) from the compromised key.
    • This provides instant partial protection while you coordinate with the customer.
  3. Limit usage

    • Apply very tight rate limits or usage caps to the compromised key to reduce potential abuse.
  4. Issue a new key for the affected customer

    • Create a new key with correct permissions.
    • Communicate directly and securely how to switch.
  5. Revoke the compromised key

    • Once the customer confirms they’ve switched, fully revoke the old key.
    • If malicious use is ongoing, you may need to revoke it immediately even before confirmation.

Even in emergencies, this phased approach keeps your response targeted and reduces unnecessary disruption.


Minimizing customer impact during rotation

To rotate and revoke keys in Unkey without breaking existing customers, focus on these operational practices:

  • Transparent communication

    • Provide clear timelines, reasons, and instructions.
    • Offer sample code snippets for updating keys.
  • Graceful error handling

    • Always return predictable HTTP status codes and structured error messages when a key fails verification.
    • Suggest corrective actions: “log in to your dashboard to generate a new key.”
  • Testing before enforcing

    • Use staging environments and test keys with expiration and rotation flows.
    • Simulate expiring or revoking keys for internal services before rolling out to customers.
  • Monitoring and alerts

    • Track spikes in 401/403 errors by key or customer.
    • Alert your team when a high number of requests start failing due to revocation or expiration.

Putting it all together

A robust key rotation and revocation strategy in Unkey typically looks like this:

  1. Design for rotation: Multiple active keys per customer, documented processes, and self-service key management.
  2. Automate verification: Use the Unkey SDK / REST API to verify keys on every request.
  3. Use dual-key windows: Always overlap old and new keys during planned rotations.
  4. Leverage Unkey features: Rate limiting, usage limits, RBAC, and automatic key expiration to manage risk without sudden breakage.
  5. Revoke safely: Only revoke keys once you’ve confirmed they’re unused, or in emergencies where risk outweighs temporary disruption.

By combining these patterns with Unkey’s API-first platform and global propagation, you can keep your APIs secure, compliant, and reliable—without surprising or breaking your existing customers during key rotations and revocations.