LLM API Key Management: Application, Security, and Rotation Best Practices

    This article explains how to obtain, manage, and secure large language model (LLM) API keys. It covers the key application flow, the trade-offs between test and production credentials, least-privilege controls such as IP allowlists and access policies, automated rotation with dual keys, correct client-side usage and error-code troubleshooting, and observability and cost governance keyed by Access Key ID. A final checklist summarizes the practices teams can apply to keep model API usage stable and controlled.

    1. Why API Keys Are the First Gate to Model Capabilities

    When integrating large model capabilities into a business system, the first thing developers encounter is not the model itself but a seemingly ordinary string: the API key. It serves three purposes. First, authentication: the server uses it to confirm which registered entity a request comes from. Second, authorization: it determines which model services, endpoints, and data scopes that entity can access. Third, usage tracking and billing attribution: all call volume, concurrency, and error rates are aggregated at the key level.

    This distinction matters: a key is not a replacement for a password, but a programmable identity credential. It appears in HTTP request headers and can be unintentionally recorded by logs, tracing systems, and frontend build artifacts. Its lifecycle management must therefore be treated as an engineering problem, not a one-time configuration step.

    2. The Application Flow: From Registration to Your First Key Pair

    The general process can be abstracted into four stages.

    1. Registration and identity verification. Developer platforms typically require registration with an email address or phone number, followed by identity verification. Individual developers generally upload an identity document, while business users provide entity materials such as business registration documents. Identity verification makes accountability traceable and is also a prerequisite for requesting higher quotas later.
    2. Create credentials in the console. After verification, go to the developer console and create a key under the key management or API management section. Some platforms also let you create an “application” first and then bind the required service types to it, with the key existing as the application’s access credential.
    3. Fill in the configuration. Common options include a key name (for human identification of its purpose, such as prod-order-service), an expiration period, an IP allowlist, and optional permission scopes.
    4. Save the key pair. The system generates a key pair consisting of an Access Key ID and a Secret Access Key. The Access Key ID is publicly identifiable and marks “who is calling”; the Secret Access Key is used for signing and is equivalent to a passphrase. It is usually displayed in full only once, at creation time, and cannot be viewed again after the dialog is closed.

    One high-frequency failure point must be emphasized here: a lost Secret Key cannot be recovered and can only be regenerated through key rotation. The creation flow itself should therefore include the step of “immediately writing it to secure storage”, for example:

    1. # Write to a permission-restricted local file immediately after creation,
    2. # so the secret does not end up in shell history or a chat window
    3. umask 077
    4. cat > ~/.config/myapp/credentials.env <<'EOF'
    5. ACCESS_KEY_ID=xxxxxxxxxxxx
    6. SECRET_ACCESS_KEY=xxxxxxxxxxxx
    7. EOF

    If the platform supports downloading a CSV backup, that file should be placed under a controlled key management process, not in personal cloud storage or a code repository.

    3. Test vs. Production Keys: Making the Trade-off

    Most platforms split keys into test and production tiers, differing mainly in quota, expiration, and review requirements. With a common setup as an example: test keys allow roughly 1,000 calls per day and expire in about 30 days, which suits local integration work and unit tests; production keys require submitting a description of the use case, and after approval grant higher call limits or exemption from daily quotas.

    The engineering recommendation is “three sets of keys, three sets of configurations”:

    • Local development key: low quota and short expiration, allowed to be rebuilt frequently, and never placed in production environment variables;
    • Staging/integration test key: the same permission model as production but with an independent quota, used for load testing and regression;
    • Production key: least privilege, bound to an IP allowlist, with call auditing enabled.

    The benefit is fault isolation: a leaked local key does not affect the production bill, and test traffic does not consume the production quota and trigger rate limiting.

    4. Least Privilege: IP Allowlists and Policy-Based Controls

    An IP allowlist is the most direct and effective way to narrow exposure. It restricts the sources of workloads to NAT egress addresses, container cluster nodes, or dedicated-line egress addresses. Even if a key is taken outside, an attacker cannot complete calls from other network environments. Note that elastic scaling changes egress addresses, so the allowlist should cover the entire possible address range rather than a single machine.

    A further step is fine-grained control through access policies, splitting permissions into several dimensions:

    • Service dimension: allow access only to specified model service categories;
    • Action dimension: distinguish read-only calls from high-cost calls that incur charges;
    • Quota dimension: set independent call limits for different business lines so a single module cannot bring down the whole system;
    • Time dimension: allow batch jobs only within business windows.

    Policies should follow “default deny, open on demand”, and permissions should be reviewed regularly to clean up keys left behind by decommissioned applications.

    5. Rotation: Treat 90 Days as a Starting Point, Not the Finish Line

    Rotating keys every 90 days is recommended, but this is only a baseline. A more reliable pattern is “dual-key parallelism”: create a new key first and complete a canary replacement in the configuration center, then revoke the old key after call success rates and error-code distributions remain stable. The whole process is transparent to the business and avoids a full-scale wave of 401 errors caused by “deleting the old key and forgetting to switch to the new one”.

    Rotation should be automated rather than driven by calendar reminders:

    1. # Pseudocode: read current credentials from a secret management service, with hot reload support
    2. def load_credentials():
    3. return {
    4. "ak": secret_store.get("llm/ak"),
    5. "sk": secret_store.get("llm/sk"),
    6. }
    7. # The application depends only on load_credentials();
    8. # rotation requires no code changes and no restart

    Supporting actions include: naming keys with a version and purpose, confirming there are no active calls before revocation, and writing rotation records into a change log for audit traceability.

    6. Correct Usage on the Client Side and Error-Code Troubleshooting

    Keys should exist only on the server side. Browsers, mobile clients, and public repositories are off-limits; if a frontend needs to connect directly, the backend should issue short-lived temporary credentials instead of handing out long-term keys.

    A minimal working request skeleton looks like this:

    1. import os, time, requests
    2. def call_model(payload):
    3. resp = requests.post(
    4. os.environ["LLM_ENDPOINT"],
    5. headers={
    6. "Authorization": f"Bearer {os.environ['LLM_API_KEY']}",
    7. "Content-Type": "application/json",
    8. },
    9. json=payload,
    10. timeout=30,
    11. )
    12. if resp.status_code == 429: # Rate limited: back off and retry
    13. time.sleep(2 ** int(resp.headers.get("Retry-After", 1)))
    14. return call_model(payload)
    15. resp.raise_for_status()
    16. return resp.json()

    The meaning of common status codes and how to handle them:

    • 401 Invalid key: the key was revoked, characters were missing during copying, environment variables are crossed, or the Access Key and Secret do not match;
    • 403 Insufficient permissions: the corresponding service is not enabled, the IP is not on the allowlist, or the policy does not permit the action;
    • 429 Rate limited: concurrency or frequency exceeds the limit, so use exponential backoff and request queuing rather than retrying immediately;
    • 503 Service overloaded: the server is under excessive pressure; combine retries with fallback to a backup model or cached results.

    The recommended troubleshooting order is fixed: first confirm the credential source (which environment variable, which configuration set), then confirm permissions and the allowlist, and finally check quota and backend health. The vast majority of production incidents occur in the first two steps.

    7. Observability and Cost Governance

    The key dimension is naturally an excellent observability slice. Using the Access Key ID as a label in logging services and monitoring alerts lets you see call volume, P95 latency, error-code share, and sudden failure spikes for each business line separately. When a key’s call curve shows an abnormal rise, it often means a leak or a code defect causing repeated calls.

    Cost governance also lands here: assign independent keys to different teams with quota caps, and pair them with daily and per-business-line usage reports to quickly identify “who used up the quota”. For batch jobs, invalid consumption can be reduced through request merging, result caching, and off-peak scheduling.

    8. Checklist

    • Use keys only on the server side; frontends always go through short-lived temporary credentials;
    • Save the Secret Key at creation; if lost, it can only be rotated;
    • Separate test and production keys so quotas and permissions do not interfere with each other;
    • Cover elastic address ranges with the allowlist, and default policies to deny;
    • Rotate with dual keys in a canary fashion, on a cycle of no more than 90 days, automated;
    • Build monitoring and cost reports with the Access Key ID as a label;
    • Troubleshoot 401/403/429/503 in a fixed order, and always retry with backoff.

    Treat key management as a routine capability of the configuration center rather than a one-time action, and model capability calls will be both stable and controllable. If an organization already uses relevant Baidu AI Cloud products, general capabilities such as key hosting, logging, and monitoring alerts can be chained into a closed loop to further reduce governance costs.