State Time-to-Live (TTL)

Manage state with time-to-live.

Introduction

Dapr enables per state set request time-to-live (TTL). This means that applications can set time-to-live per state stored, and these states cannot be retrieved after expiration.

Only a subset of Dapr state store components are compatible with state TTL. For supported state stores simply set the ttlInSeconds metadata when publishing a message. Other state stores will ignore this value.

Some state stores can specify a default expiration on a per-table/container basis. Please refer to the official documentation of these state stores to utilize this feature of desired. Dapr support per-state TTLs for supported state stores.

Native state TTL support

When state time-to-live has native support in the state store component, Dapr simply forwards the time-to-live configuration without adding any extra logic, keeping predictable behavior. This is helpful when the expired state is handled differently by the component. When a TTL is not specified the default behavior of the state store is retained.

Persisting state (ignoring an existing TTL)

To explicitly persist a state (ignoring any TTLs set for the key), specify a ttlInSeconds value of -1.

Supported components

Please refer to the TTL column in the tables at state store components.

Example

State TTL can be set in the metadata as part of the state store set request:

  1. curl -X POST -H "Content-Type: application/json" -d '[{ "key": "key1", "value": "value1", "metadata": { "ttlInSeconds": "120" } }]' http://localhost:3500/v1.0/state/statestore
  1. Invoke-RestMethod -Method Post -ContentType 'application/json' -Body '[{"key": "key1", "value": "value1", "metadata": {"ttlInSeconds": "120"}}]' -Uri 'http://localhost:3500/v1.0/state/statestore'
  1. from dapr.clients import DaprClient
  2. with DaprClient() as d:
  3. d.save_state(
  4. store_name="statestore",
  5. key="myFirstKey",
  6. value="myFirstValue",
  7. metadata=(
  8. ('ttlInSeconds', '120')
  9. )
  10. )
  11. print("State has been stored")

Save the following in state-example.php:

  1. <?php
  2. require_once __DIR__.'/vendor/autoload.php';
  3. $app = \Dapr\App::create();
  4. $app->run(function(\Dapr\State\StateManager $stateManager, \Psr\Log\LoggerInterface $logger) {
  5. $stateManager->save_state(store_name: 'statestore', item: new \Dapr\State\StateItem(
  6. key: 'myFirstKey',
  7. value: 'myFirstValue',
  8. metadata: ['ttlInSeconds' => '120']
  9. ));
  10. $logger->alert('State has been stored');
  11. });

See this guide for a reference on the state API.

Last modified November 12, 2021 : Merge pull request #1949 from willtsai/az-staticwebapp-versioning (c40e456)