Introduction
When we talk about the “Key Lifecycle” in Tyk, we are actually referring to the lifecycle of the Session stored in Redis. The Key is simply the identifier used to look up that Session. Keeping an expired Session in Redis for a period of time can be useful for various reasons:- Graceful Renewal & Better UX: Enables the Gateway to return specific
Token Expirederrors rather than genericInvalid Tokenresponses, allowing client applications to trigger silent refresh flows without forcing users to log in again. - Audit & Troubleshooting: Preserves session data post-expiration to aid in compliance and debugging, making it easier to trace requests and correlate logs for issues occurring near the expiration time.
- Asynchronous Analytics & Billing: Ensures background workers can accurately attribute final requests to the correct user or organization, preventing data loss in asynchronous analytics and billing processes.
- Quota Preservation Across Renewals: Retains quota data for users with long-term limits but short-lived access tokens, allowing renewed tokens to link to existing quota buckets without accidentally resetting usage.
- Security & Fraud Detection: Provides context for security systems to monitor replay attacks, identifying if an expired token is suddenly flooded with requests rather than just logging generic errors.
Expiration vs. Deletion
To understand Tyk’s lifecycle controls, you must understand the difference between a Session expiring and a Session being deleted:- Expiration (expires): This is a Unix timestamp stored inside the Session. When a request arrives, Tyk checks if the current time is past this timestamp. If it is, Tyk rejects the request. The Session is “expired” and access is denied, even if the data still exists in Redis.
- Deletion (Redis TTL): This is the physical removal of the Session data from your Redis database. Tyk calculates a Time-To-Live (TTL) and passes it to Redis. When the TTL reaches zero, Redis automatically deletes the data.
Preferred Controls (Tyk 5.13.0+)
Starting in Tyk 5.13.0, Tyk introduced explicit controls that separate the concept of expiration from deletion. This allows you to deny access at a specific time, but retain the Session data in Redis for auditing, analytics, or delayed cleanup. In the Tyk Dashboard, these settings are exposed under the Behaviour on key expiry section when creating or editing a key or policy with an expiration time.1. Set the Expiration
expires: A Unix timestamp indicating exactly when the Session becomes invalid. If set to0or-1, the Session never expires.
2. Define the Post-Expiry Action
post_expiry_action: Defines what happens to the data in Redis after theexpirestimestamp is reached. In the Tyk Dashboard, this corresponds to the Behaviour on key expiry radio options:delete: The Redis TTL is set to match theexpirestimestamp. The moment the Session expires, Redis physically deletes it.retain: The Session is kept in Redis after it expires. You must also configure a grace period.
3. Configure the Grace Period
post_expiry_grace_period: If the action isretain, this defines how long (in seconds) the Session is kept in Redis after expiration.
- Retain for specific period (
post_expiry_grace_period > 0): Specify a duration before deletion. You can select or enter a human-readable timeframe (for example,1h,30d, or6h30m20s), which the Dashboard converts into integer seconds (for example,86400for 24 hours). - Retain forever (
post_expiry_grace_period: -1): Keeps the Session in Redis indefinitely (no post-expiry TTL is set) until manually deleted. - Use API or gateway default (Default,
post_expiry_grace_period: 0): Falls back to the legacy controls (custom API key lifetime or Gateway global session lifetime).
expires is tomorrow, and post_expiry_grace_period is 86400 (24 hours), the Session will be denied access tomorrow, but the Session data will remain in Redis for one additional day before being physically deleted.
Legacy Controls
Tyk falls back to the legacy controls in three cases:- You are running an older Tyk version that predates these fields.
post_expiry_actionis not set, even ifpost_expiry_grace_periodhas a value. The grace period is only used once the action is set to retain.post_expiry_actionis set toretainandpost_expiry_grace_periodis0.
x-tyk-api-gateway) in the API definition contains an option to set a customKeyLifetime for all keys (Sessions) created that grant access to the API:
If the lifetime (
value) is set to 0s then sessions will be assigned a TTL of -1 and will not be automatically deleted from Redis.
If
respectValidity is set to false and the value is lower than the value assigned for Session expiry then the Session will be deleted before it becomes invalid.session_lifetime (for value, in seconds) and session_lifetime_respects_key_expiration (for respectValidity):
Configure session lifetime in Tyk DashboardThe Tyk Dashboard UI does not have form fields for
customKeyLifetime (Tyk OAS APIs) or session_lifetime (Tyk Classic APIs).Configure this setting through the raw API definition or via API:- Tyk OAS APIs: Update the raw OpenAPI definition in the API Designer, or import an updated OAS definition.
- Tyk Classic APIs: Select the Raw Definition tab in the API Designer to edit
session_lifetimeandsession_lifetime_respects_key_expiration. - API: Update the definition with the Tyk Dashboard API or Tyk Gateway API.
Gateway Level Settings
In some environments, administrators need to enforce a strict maximum lifetime for all sessions across the entire Gateway, regardless of what individual users or policies configure. You can enforce this behaviour in yourtyk.conf file (or by using the equivalent environment variables):
global_session_lifetime: The maximum allowed lifetime (in seconds) for any Session in Redis. If set to0then sessions will be assigned a TTL of -1 and will not be automatically deleted from Redis.force_global_session_lifetime: When set totrue, the global lifetime will be enforced, taking precedence over all other lifecycle controls (post_expiry_action,customKeyLifetime, andexpires). The Redis TTL for every Session will be strictly set to theglobal_session_lifetime.session_lifetime_respects_key_expiration: if set totrue, the Session’s TTL is the later ofexpiresor the per-API custom key lifetime. This iscustomKeyLifetime.valuefor Tyk OAS, orsession_lifetimefor Tyk Classic.
If the Global Session Lifetime is enforced, this will be applied to all Sessions, even those with no expiry.
Summary of Session Lifetime Calculation
With the ongoing support for legacy controls it is possible to get confused how best to configure session lifetime to manage your Redis storage. We recommend using the more intuitive post-expiry action and grace period controls. This table summarises the effect of different combinations of controls.Temporarily revoking access to a key
If you need to revoke access immediately without waiting for expiration or deletion, you can use theis_inactive flag:
is_inactive: A boolean flag on the Session. When set totrue, Tyk rejects requests using this Session as if it has expired. Setting this back tofalsewill reactivate the Session. The Session data remains in Redis until its TTL expires. This is useful for temporarily suspending a user.
OAuth 2.0 Token Lifecycle
If you are using OAuth 2.0, it is important to understand how OAuth tokens interact with Tyk’s session lifecycle controls. When Tyk generates an OAuth access token, it creates a standard Session object. The initial expiration time of this session is controlled by the globaloauth_token_expire Gateway configuration. Once this timestamp is reached, the access token’s session is subject to the standard session lifecycle controls described above, which determine its physical retention in Redis.
Conversely, refresh tokens are not Session objects. They do not use these session lifecycle controls and are physically deleted from Redis exactly when their oauth_refresh_token_expire TTL is reached.
The
oauth_token_expired_retain_period settingYou may notice the global Gateway configuration option oauth_token_expired_retain_period. This setting does not control the Redis TTL or the retention of the actual Session data. Instead, it controls a background cleanup job that removes expired tokens from an internal tracking list used by the OAuth client.