Database / Azure Cosmos DB interview questions
What is Time to Live (TTL) in Cosmos DB and how do you configure it?
Time to Live (TTL) is a built-in expiry mechanism that automatically deletes items after a specified number of seconds from their last modification timestamp. This is useful for session data, temporary tokens, audit logs with retention windows, or any data with a known shelf life. Cosmos DB's TTL deletion is handled by a background process and does not consume your provisioned RU/s — it is essentially free in terms of throughput impact.
TTL is configured at two levels:
- Container-level TTL (DefaultTimeToLive) — Set this to a positive integer (seconds) to give all items a default TTL. Set to
-1to enable TTL at the container level but make each item's TTL opt-in (items without attlproperty never expire). If this property is absent on the container, TTL is completely disabled. - Item-level TTL (ttl property) — Set a
ttlfield on individual items to override the container default. An item-levelttl: -1means that item never expires regardless of the container default.
An example showing how container default and item override interact:
// Container: DefaultTimeToLive = 3600 (1 hour) // This item expires in 1 hour (inherits container default) { "id": "session-1", "userId": "u123" } // This item expires in 5 minutes (item override) { "id": "temp-token", "userId": "u456", "ttl": 300 } // This item never expires (item override = -1) { "id": "permanent-record", "userId": "u789", "ttl": -1 }
TTL deletion happens within a few seconds to minutes after the expiry time. It is approximate, not exact — do not rely on it for precision timing like security token enforcement (validate the expiry claim in the token itself instead).
More Related questions...