Introducing a new way to review your PRs.

Read the announcement

zipstack / unstract

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

View on GitHub

28 documents · Updated Nov 23, 2026

docs / api-key-usage

API key usage and lifecycle

The API-key usage domain records successful key use, keeps recent usage data, and exposes that data with key management APIs. It also gives platform and deployment keys a shared lifecycle for expiration and secret rotation. See Backend API platform for the wider API boundary.

Domain scope

The domain connects key authentication to key management. It records only accepted requests, links deployment calls to the key that authorized them, and gives operators enough data to find unused, idle, expiring, or expired keys.

The main key types are:

  • Platform API keys, which authenticate organization-scoped platform API requests.
  • Global API deployment keys, which authenticate calls to API deployments and can report which deployments used them.
  • Registered key types, which can join the common usage and summary model when they provide the required organization and lifecycle fields.

The domain does not treat a key's secret as usage data. Key management returns masked values in lists and exposes the current value in the existing detail flows, while audit events never contain a secret.

This page extends the Backend API platform with usage and key lifecycle rules. Read Versioned backend APIs and domain modules for deployment authentication, and Platform audit events for the audit records emitted by expiry and rotation. References: backend/…/README.md• L1-9, backend/…/expiry.py• L40-60, backend/…/rotation.py• L60-65

Key lifecycle

Each key moves through authentication, use tracking, and management actions. The lifecycle keeps access control separate from usage display: a key must pass its normal ownership, scope, active-state, and expiry checks before its request can count.

Authentication and usage recording

Authentication accepts the current secret or, during a grace period, the latest previous secret. After the request passes all checks, the platform middleware records platform-key use; API deployment validation records global-key use together with the deployment ID. A rejected or expired key is not counted. References: backend/…/custom_auth_middleware.py• L112-215, backend/…/key_helper.py• L70-129, backend/…/deployment_helper.py• L104-133

Expiration

expires_at is optional. A null value means that the key has no expiry. A date must be in the future when it is set, and setting, changing, or clearing the date produces a key.expiry_set audit event with the before and after values.

An expired key receives a 401 response and does not create a usage record. The platform and global-key paths keep their established error body shapes, so expiration adds a clear failure without changing unknown-key handling. References: backend/…/expiry.py• L14-60, backend/…/serializers.py• L42-68, backend/…/serializers.py• L122-175, backend/…/custom_auth_middleware.py• L138-152, backend/…/key_helper.py• L90-117

Secret rotation

Rotation replaces the current secret and can keep the prior secret valid for a short grace period. Supported periods are none, one hour, 24 hours, and seven days. Only the latest prior secret is retained, and a second rotation replaces the earlier grace record.

The rotation flow locks the key while it changes the secret. This prevents concurrent rotations from restoring a secret that another rotation already disabled. A deactivated key rejects both secrets, and the old secret cannot rotate the key itself. References: backend/…/rotation.py• L16-80, backend/…/views.py• L138-162, backend/…/views.py• L215-238

Usage data flow

Usage uses a fast transient path for requests and a durable aggregate path for reads. This keeps authentication independent from database writes while still making recent counts visible in key pages.

Redis state

Each successful use updates Redis counters for daily calls and the last-use time. A deployment-backed key also updates a caller counter and caller last-use time. The update is atomic, and a bounded Redis timeout means a Redis problem can lose a count but cannot block or fail the authenticated request.

The first use in a flush interval starts a background flush across processes. A read also asks for a flush before it calculates usage. The default interval is five minutes and the default Redis wait limit is 0.5 seconds. References: backend/…/recorder.py• L1-19, backend/…/recorder.py• L119-185, backend/…/base.py• L471-482

Batch application

The flush moves pending Redis state into a named batch before it writes to the database. It then applies the batch in a transaction and removes the Redis batch only after the transaction commits. An applied-batch token makes a retry safe when a process stops after the database write but before Redis cleanup.

The durable store keeps daily key counts, daily deployment callers, and the latest use time. Daily data covers the last 30 UTC days. Last-use data is kept longer so the system can still identify a key that has been idle for more than 90 days. A batch that fails repeatedly is set aside for inspection instead of blocking later batches. References: backend/…/flush.py• L1-19, backend/…/flush.py• L114-157, backend/…/models.py• L5-101, backend/…/constants.py• L9-50

This diagram shows how an accepted request becomes durable usage data and then becomes a key-page response.

flowchart LR
    A[Accepted key request] --> B[Atomic Redis counters]
    B --> C[Named pending batch]
    C --> D[Database transaction]
    D --> E[Daily counts and last-use data]
    E --> F[Read refresh]
    F --> G[Key list, history, callers, or summary]

Usage reads and API exposure

The read layer turns the shared usage data into status fields, time series, caller lists, and organization summaries. Key endpoints refresh pending data first, so a recent call normally appears without waiting for the periodic flush.

Usage views

Both key lists and detail responses include last_used_at, calls_30d, usage_status, expires_at, and the end of the prior-secret grace period. History returns 30 UTC days in oldest-first order and includes zero-call days. Global deployment keys also expose callers from the same 30-day window; deleted or no-longer-visible deployments keep their counts but lose their names.

The status order is significant: expired, expiring within seven days, never used, idle after 90 days, and active. The summary counts active keys once under the same status used by the lists and groups the result by registered key type. References: backend/…/reads.py• L30-64, backend/…/reads.py• L67-175, backend/…/serializers.py• L10-91, backend/…/views.py• L12-25

Access boundaries

Usage reads keep the permissions of the key-management surface. Organization admins can read platform-key usage and the cross-type summary. Global-key usage is also available to members who may manage keys, but only for member-created keys and deployments they may still use. A caller name is shown only when the reader may see that deployment.

The key lists and detail endpoints remain owned by their key domains. The usage app adds the summary endpoint at GET platform/key-usage/summary/; the key domains add history, caller, and lifecycle actions to their own routes. References: backend/…/README.md• L22-51, backend/…/urls.py• L1-7, backend/…/views.py• L36-111, backend/…/views.py• L47-197

Schema evolution

The usage schema is shared by key types without foreign keys to key tables. Each durable row identifies a key by key_type and key_id, while organization ownership supports tenant-scoped reads. This lets history survive key deletion until its daily data ages out and lets an external key type use the same storage model.

Registered key types

The registry supplies the key query for each organization. Built-in platform and global deployment keys register at app startup. A new key type must provide rows with an ID, active state, and optional expiry, record successful authentication with its type and organization, and use the shared read helpers for its list and history views.

This contract keeps summary counts and status rules consistent when new key types join the domain. It also makes the by_type response extensible without changing the meaning of existing entries. References: backend/…/registry.py• L1-47, backend/…/README.md• L229-246

Published API contract

The README and schema annotations define the public response shapes. Usage fields and lifecycle fields are additive to existing key responses. Schema migrations add the durable usage tables, applied-batch tracking, and day indexes that support the 30-day read window and safe batch retries.

Changes to field names, status order, route shapes, or key-type registration affect clients and all key serializers. The schema tests protect the shared fields and endpoint shapes for both built-in key types. References: backend/…/README.md• L7-20, backend/…/test_schema.py• L29-76, backend/…/0001_initial.py• L14-135, backend/…/0002_applied_batch.py• L6-23, backend/…/0003_day_indexes.py• L6-20

Change checklist

When these files or sections are changed, remember to consider these:

  • When adding a key type, register its organization query and use the same key_type value in authentication, storage, serializers, and summary output.
  • When changing expiry or rotation fields, update both key models, write serializers, detail serializers, authentication checks, and schema annotations.
  • When changing Redis field shapes or batch rules, keep the recorder and flush parser in lockstep. Preserve the applied-batch guard for crash retries.
  • When changing retention or status thresholds, update the read window, prune behavior, summary counts, and public descriptions together.
  • When changing caller visibility, preserve the rule that counts may remain visible while deployment names are hidden.

Important failure modes

TriggerConsequenceGuard
Redis is slow or unavailable during authenticationThe request succeeds but that use is not countedShort Redis timeouts and best-effort recording
A process stops after a batch database commitRedis still contains the batchApplied-batch token prevents a second count
A batch repeatedly fails while backends are healthyThat batch stops blocking later batches and is set asideFive-attempt limit with temporary Redis retention
A database or Redis outage occurs during flushingPending batches wait for a later flush without being marked badBackend health check distinguishes outage from batch errors
A key expires or is inactiveAuthentication returns 401 and usage is not recordedLifecycle checks run before record_key_use
A member loses access to a deploymentCaller counts remain, but its display names become nullNames are resolved through the reader's visible deployment set

Key files

FileWhy to read it
backend/…/README.mdPublished endpoint, field, status, retention, and extension contract
backend/…/recorder.pyRequest-time usage recording and Redis trigger behavior
backend/…/flush.pyBatch movement, durable writes, retry safety, and retention pruning
backend/…/reads.pyStatus calculation, history, caller views, and summaries
backend/…/registry.pyShared contract for built-in and added key types
backend/…/models.pyDurable usage and batch state model
backend/…/views.pyPlatform-key lifecycle and usage endpoints
backend/…/views.pyGlobal-key scope, caller reads, lifecycle, and usage endpoints
backend/…/custom_auth_middleware.pyPlatform-key authentication boundary and recording point
backend/…/deployment_helper.pyGlobal-key authentication boundary and deployment attribution