PostgreSQL

Detailed information on the PostgreSQL state store component

Note

This is the v2 of the PostgreSQL state store component, which contains some improvements to performance and reliability. New applications are encouraged to use v2.

The PostgreSQL v2 state store component is not compatible with the v1 component, and data cannot be migrated between the two components. The v2 component does not offer support for state store query APIs.

There are no plans to deprecate the v1 component.

This component allows using PostgreSQL (Postgres) as state store for Dapr, using the “v2” component. See this guide on how to create and apply a state store configuration.

  1. apiVersion: dapr.io/v1alpha1
  2. kind: Component
  3. metadata:
  4. name: <NAME>
  5. spec:
  6. type: state.postgresql
  7. # Note: setting "version" to "v2" is required to use the v2 of the component
  8. version: v2
  9. metadata:
  10. # Connection string
  11. - name: connectionString
  12. value: "<CONNECTION STRING>"
  13. # Timeout for database operations, as a Go duration or number of seconds (optional)
  14. #- name: timeout
  15. # value: 20
  16. # Prefix for the table where the data is stored (optional)
  17. #- name: tablePrefix
  18. # value: ""
  19. # Name of the table where to store metadata used by Dapr (optional)
  20. #- name: metadataTableName
  21. # value: "dapr_metadata"
  22. # Cleanup interval in seconds, to remove expired rows (optional)
  23. #- name: cleanupInterval
  24. # value: "1h"
  25. # Maximum number of connections pooled by this component (optional)
  26. #- name: maxConns
  27. # value: 0
  28. # Max idle time for connections before they're closed (optional)
  29. #- name: connectionMaxIdleTime
  30. # value: 0
  31. # Controls the default mode for executing queries. (optional)
  32. #- name: queryExecMode
  33. # value: ""
  34. # Uncomment this if you wish to use PostgreSQL as a state store for actors (optional)
  35. #- name: actorStateStore
  36. # value: "true"

Warning

The above example uses secrets as plain strings. It is recommended to use a secret store for the secrets as described here.

Spec metadata fields

Authenticate using a connection string

The following metadata options are required to authenticate using a PostgreSQL connection string.

FieldRequiredDetailsExample
connectionStringYThe connection string for the PostgreSQL database. See the PostgreSQL documentation on database connections for information on how to define a connection string.“host=localhost user=postgres password=example port=5432 connect_timeout=10 database=my_db”

Authenticate using Microsoft Entra ID

Authenticating with Microsoft Entra ID is supported with Azure Database for PostgreSQL. All authentication methods supported by Dapr can be used, including client credentials (“service principal”) and Managed Identity.

FieldRequiredDetailsExample
useAzureADYMust be set to true to enable the component to retrieve access tokens from Microsoft Entra ID.“true”
connectionStringYThe connection string for the PostgreSQL database.
This must contain the user, which corresponds to the name of the user created inside PostgreSQL that maps to the Microsoft Entra ID identity. This is often the name of the corresponding principal (for example, the name of the Microsoft Entra ID application). This connection string should not contain any password.
“host=mydb.postgres.database.azure.com user=myapplication port=5432 database=my_db sslmode=require”
azureTenantIdNID of the Microsoft Entra ID tenant“cd4b2887-304c-…”
azureClientIdNClient ID (application ID)“c7dd251f-811f-…”
azureClientSecretNClient secret (application password)“Ecy3X…”

Other metadata options

FieldRequiredDetailsExample
tablePrefixNPrefix for the table where the data is stored. Can optionally have the schema name as prefix, such as public.prefix“prefix“, “public.prefix_”
metadataTableNameNName of the table Dapr uses to store a few metadata properties. Defaults to dapr_metadata. Can optionally have the schema name as prefix, such as public.dapr_metadata“dapr_metadata”, “public.dapr_metadata”
timeoutNTimeout for operations on the database, as a Go duration. Integers are interpreted as number of seconds. Defaults to 20s“30s”, 30
cleanupIntervalNInterval, as a Go duration or number of seconds, to clean up rows with an expired TTL. Default: 1h (1 hour). Setting this to values <=0 disables the periodic cleanup.“30m”, 1800, -1
maxConnsNMaximum number of connections pooled by this component. Set to 0 or lower to use the default value, which is the greater of 4 or the number of CPUs.“4”
connectionMaxIdleTimeNMax idle time before unused connections are automatically closed in the connection pool. By default, there’s no value and this is left to the database driver to choose.“5m”
queryExecModeNControls the default mode for executing queries. By default Dapr uses the extended protocol and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as PGBouncer. In this case, it may be preferrable to use exec or simple_protocol.“simple_protocol”
actorStateStoreNConsider this state store for actors. Defaults to “false”“true”, “false”

Setup PostgreSQL

  1. Run an instance of PostgreSQL. You can run a local instance of PostgreSQL in Docker with the following command:

    1. docker run -p 5432:5432 -e POSTGRES_PASSWORD=example postgres

    This example does not describe a production configuration because it sets the password in plain text and the user name is left as the PostgreSQL default of “postgres”.

  2. Create a database for state data.
    Either the default “postgres” database can be used, or create a new database for storing state data.

    To create a new database in PostgreSQL, run the following SQL command:

    1. CREATE DATABASE my_dapr;

Advanced

Differences between v1 and v2

The PostgreSQL state store v2 was introduced in Dapr 1.13. The pre-existing v1 remains available and is not deprecated.

In the v2 component, the table schema has been changed significantly, with the goal of increasing performance and reliability. Most notably, the value stored by Dapr is now of type BYTEA, which allows faster queries and, in some cases, is more space-efficient than the previously-used JSONB column.
However, due to this change, the v2 component does not support the Dapr state store query APIs.

Also, in the v2 component, ETags are now random UUIDs, which ensures better compatibility with other PostgreSQL-compatible databases, such as CockroachDB.

Because of these changes, v1 and v2 components are not able to read or write data from the same table. At this stage, it’s also impossible to migrate data between the two versions of the component.

Displaying the data in human-readable format

The PostgreSQL v2 component stores the state’s value in the value column, which is of type BYTEA. Most PostgreSQL tools, including pgAdmin, consider the value as binary and do not display it in human-readable form by default.

If you want to inspect the value in the state store, and you know it’s not binary (for example, JSON data), you can have the value displayed in human-readable form using a query like the following:

  1. -- Replace "state" with the name of the state table in your environment
  2. SELECT *, convert_from(value, 'utf-8') FROM state;

TTLs and cleanups

This state store supports Time-To-Live (TTL) for records stored with Dapr. When storing data using Dapr, you can set the ttlInSeconds metadata property to indicate after how many seconds the data should be considered “expired”.

Because PostgreSQL doesn’t have built-in support for TTLs, this is implemented in Dapr by adding a column in the state table indicating when the data is to be considered “expired”. Records that are “expired” are not returned to the caller, even if they’re still physically stored in the database. A background “garbage collector” periodically scans the state table for expired rows and deletes them.

You can set the deletion interval of expired records with the cleanupInterval metadata property, which defaults to 3600 seconds (that is, 1 hour).

  • Longer intervals require less frequent scans for expired rows, but can require storing expired records for longer, potentially requiring more storage space. If you plan to store many records in your state table, with short TTLs, consider setting cleanupInterval to a smaller value; for example, 5m (5 minutes).
  • If you do not plan to use TTLs with Dapr and the PostgreSQL state store, you should consider setting cleanupInterval to a value <= 0 (for example, 0 or -1) to disable the periodic cleanup and reduce the load on the database.

Last modified March 21, 2024: Merge pull request #4082 from newbe36524/v1.13 (f4b0938)