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?

9 min read

Rotating and revoking API keys is a critical part of keeping your platform secure, but it can easily cause downtime or broken integrations if it’s done abruptly. With Unkey, you can design a key lifecycle that lets you rotate and revoke keys safely, minimize disruption, and give customers time to migrate.

This guide walks through practical strategies to rotate and revoke keys in Unkey without breaking existing customers, using Unkey’s API-first design, rate limiting, automatic expiration, and usage controls.


Why key rotation and revocation matter

Key rotation and revocation are crucial for:

  • Security – Limiting the blast radius of leaked or abused keys.
  • Compliance – Many standards require periodic key rotation.
  • Operational resilience – Letting you change infrastructure or secret management without touching customer code all at once.

The challenge is doing this without:

  • Forcing every customer to update immediately.
  • Breaking long-lived integrations or scheduled jobs.
  • Creating confusing states where “some calls work, some don’t.”

Unkey’s flexible API, usage controls, and automatic expiration make it possible to roll out changes gradually, with clear windows for migration.


Key lifecycle best practices in Unkey

Before getting into specific rotation and revocation workflows, establish a consistent key lifecycle pattern:

  1. Issue – Create a key per customer, app, or environment.
  2. Use & monitor – Track usage, rate limit, and proactively detect abuse.
  3. Prepare for rotation – Issue a new key while the old one still works.
  4. Transition – Run a dual-key period where both keys are valid.
  5. Decommission – Revoke or let the old key expire automatically.

Aligning your processes with this pattern helps you use Unkey’s features—like automatic expiration and usage limits per key—to manage changes safely.


Strategy 1: Use dual-key rotation to avoid downtime

The safest pattern for rotating keys in Unkey is dual-key rotation: issue a new key, keep the old key valid for a defined grace period, and then revoke or let it expire.

Step 1: Create a new key for the customer

Using Unkey’s SDK or REST API, create a new key for the same customer or application. With Unkey’s API-first design, you can fully automate this in your backend or internal tools.

Key details to decide:

  • Scope/permissions – Match or explicitly refine the existing key’s permissions.
  • Expiration – Use a reasonable TTL to encourage future rotation.
  • Usage limits – Optionally cap usage per key.

Example (TypeScript snippet pattern):

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

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

// Pseudocode – actual fields depend on your schema
const newKey = await unkey.keys.createKey({
  // ... customer / workspace / permissions ...
  // expiration / usage config
});

Return the new key via:

  • Your SaaS dashboard.
  • A “Regenerate API key” endpoint.
  • Support-assisted workflows for managed customers.

Step 2: Keep the old key valid during a migration window

Do not immediately revoke the old key. Instead:

  • Set or adjust its expiration (if applicable).
  • If you want more control, apply usage-limits per key to reduce risk during the overlap period.
  • Optionally tighten permissions on the old key if it previously had overly broad access.

This dual-key period lets customers:

  • Update environment variables.
  • Redeploy services.
  • Verify functionality with the new key in staging and production.

Step 3: Monitor usage and adoption

During the migration window, monitor key usage:

  • If only the old key is being used: customers likely haven’t migrated yet.
  • If usage gradually moves to the new key: rotation is progressing successfully.
  • If both keys are active: some services may still be rolling out updates.

Unkey’s multi-cloud, globally distributed architecture ensures verification and rate limiting are fast worldwide, so monitoring usage patterns won’t affect latency.

Step 4: Revoke or let the old key expire

Once the migration window ends:

  • Preferred: Let the old key’s automatic expiration disable it in a predictable way.
  • Alternatively: Use the Unkey API to explicitly revoke the old key.

This hard cutoff is where you might see failures if some customers haven’t updated. To reduce surprises:

  • Communicate the exact cut-off date and time up front.
  • Remind customers as the expiration date approaches.
  • Offer a manual extension path for key rotation in exceptional cases.

Strategy 2: Use automatic key expiration to enforce safe rotation

Unkey supports automatic key expiration, which is ideal for planning regular, predictable rotations:

  • When creating new keys, always assign an expiration time.
  • Communicate to customers that their keys have a fixed lifetime.
  • Encourage them to build rotation into their deployment pipeline, rather than treating keys as permanent.

Benefits:

  • Keys don’t live forever, reducing the risk of long-term leaks.
  • You can define standard rotation intervals (e.g., every 90 days).
  • Customers are nudged into good operational hygiene without forced downtime.

Pair this with usage limits per key to guard against abuse while the key is active.


Strategy 3: Use usage limits and rate limiting for progressive decommissioning

Sometimes immediate revocation is too aggressive, but you still want to reduce risk quickly. In Unkey, combine:

  • Usage limits per key – Set a maximum number of calls per key, with optional periodic refill.
  • Global rate limiting – Configure per-customer or per-key rate limits for abuse prevention.

A safe decommissioning pattern:

  1. Lower rate limits on the old key gradually.
  2. Cap total usage with a usage limit per key (e.g., “old key can only handle a limited number of calls while customers migrate”).
  3. Keep the new key fully unrestricted (within normal plan limits).

This way, even if a leaked or misused old key is still in the wild, it can’t be abused at scale, giving customers time to switch over.


Strategy 4: Handling emergency revocation (leaks or abuse)

In an emergency—like a leaked key posted publicly—you may need immediate revocation.

Use a stepped approach to reduce blast radius while preserving as much continuity as possible:

  1. Instantly revoke the compromised key

    • Use the Unkey API to disable the key so all further requests are rejected.
    • This protects your infrastructure and other customers.
  2. Issue a replacement key

    • Generate a new key with appropriate permissions.
    • Share it through your secure channel (dashboard, customer portal, etc.).
  3. Communicate clearly

    • Inform affected customers about:
      • What happened.
      • When the old key was revoked (with timestamp).
      • What they need to update (e.g., environment variables, CI secrets).
  4. Tighten future controls

    • Shorten expiration for keys with similar privileges.
    • Add or lower usage limits per key.
    • Tune rate limiting thresholds for that customer or endpoint.

This pattern protects your platform while giving customers a clear, actionable recovery path.


Minimizing customer breakage with good communication

Even the best technical strategy can fail if customers are surprised. Combine Unkey’s controls with a communication plan:

  • Announce rotation windows in advance

    • Include the exact date and time old keys will expire or be revoked.
    • Provide instructions for generating and installing new keys.
  • Show state in your dashboard

    • Mark keys as:
      • Active
      • Deprecated / scheduled for expiration
      • Expired / revoked
    • Provide timestamps and recommended actions.
  • Offer self-service regeneration

    • Use Unkey’s API-first design to let customers:
      • Create new keys.
      • See expiration dates.
      • Deactivate their own unused keys.
  • Grace periods and reminders

    • Add extra time before hard revocation for high-value or large customers.
    • Automate reminders as expiration nears.

Implementation tips when verifying keys with Unkey

When integrating Unkey’s verification in your backend, design your code to handle rotation and revocation gracefully.

A typical verification flow (simplified):

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

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

export async function verifyIncomingKey(apiKey: string) {
  const { valid, error, /* ...any metadata you use... */ } =
    await unkey.keys.verifyKey({ key: apiKey });

  if (error) {
    // Handle network or service errors.
    // You may want to fail closed for sensitive endpoints.
    throw new Error("Verification service unavailable");
  }

  if (!valid) {
    // Reject unauthorized or revoked/expired keys.
    throw new Error("Unauthorized");
  }

  // Proceed with authorized request.
}

Best practices:

  • Fail clearly: When valid is false, return specific HTTP status codes (e.g., 401 Unauthorized, 403 Forbidden) so customers know the key is invalid or revoked.
  • Expose useful metadata: If you attach customer IDs or roles to keys, use that to:
    • Identify which customer needs to rotate.
    • Drive custom rate limiting and usage tracking.
  • Log invalid key usage: To detect late adopters who keep using revoked keys.

Putting it all together: Example rotation playbook

Here’s a concrete, repeatable playbook you can adopt for your product:

  1. Standardize key TTL

    • All new production keys have a fixed expiration (e.g., 90 days).
    • Document this in your onboarding and docs.
  2. Enable customers to self-rotate

    • Dashboard button: “Generate new API key.”
    • Display:
      • Current key(s)
      • Expiration date
      • Status (active / expiring / expired)
  3. Dual-key migration

    • When a new key is created, mark the old key as “deprecated” with a future expiration date.
    • Both keys stay valid until expiration.
  4. Monitor and enforce

    • Use Unkey’s rate limiting and usage limits per key to:
      • Prevent abuse from old keys.
      • Detect when legacy keys are still being used heavily.
  5. Cut over and clean up

    • When the old key expires:
      • Requests with the old key return 401/403.
      • Logs and observability show which customers are still using it.
    • Encourage those customers to rotate immediately.
  6. Emergency override

    • In case of a leak, revoke immediately and bypass the normal schedule.

This approach uses Unkey’s core strengths—API-first design, global rate limiting, automatic expiration, and per-key usage limits—to keep your API secure while giving customers the flexibility to update on their own timeline.


Summary

To rotate and revoke keys in Unkey without breaking existing customers:

  • Use dual-key rotation with a defined grace period.
  • Rely on automatic key expiration to enforce predictable rotations.
  • Apply usage limits per key and rate limiting to mitigate risk during transitions.
  • Design your verification flow to clearly handle invalid, expired, or revoked keys.
  • Communicate proactively and give customers self-service tools to manage their keys.

By combining these patterns with Unkey’s developer-friendly platform, you can maintain strong security while keeping your customers’ integrations stable and reliable.