Help topics

Use a key-value model to store values and counters

A key-value namespace stores small values by key, and each key can expire. Use one for sessions, feature flags, rate limits and high-traffic counters.

Before you start

  • Morphic Pro is required. Without it, Key-value shows as locked under Models.
  • You need the WordPress Administrator role to create a namespace.

Create a namespace

  1. Go to Morphic > Models.
  2. In the Key-value group, select New namespace.
  3. In Name, enter a name, for example Sessions.
  4. Select Create key-value namespace.

Result: Morphic opens the new namespace. Add keys to it from the Key-value page.

Add a key

  1. Go to the Key-value page.
  2. Select the namespace in the list.
  3. Select New key.
  4. In Key, enter the key.
  5. In Value (JSON), enter the value as JSON, for example 42, "text" or {"a": 1}.
  6. In Expires after, enter a time such as 30m, 2h or 7d. Leave it empty to use the namespace default.
  7. Select Save.

Result: the key appears in the table with its Key, Value, Rev and Expires. A key with no expiry shows never.

Store a key over the API

Write a key with PUT to kv/<namespace>/entry. The body holds key, value and ttl. A ttl such as 30m sets the expiry.

curl -u "$USER:$PASS" -X PUT "https://example.com/wp-json/morphic/v1/kv/sessions/entry" -H "Content-Type: application/json" -d '{"key":"user/42","value":{"cart":3},"ttl":"30m"}'

Increment a counter with POST to kv/<namespace>/incr. The body holds key and delta. If you leave out delta, Morphic adds 1.

curl -u "$USER:$PASS" -X POST "https://example.com/wp-json/morphic/v1/kv/views/incr" -H "Content-Type: application/json" -d '{"key":"art/1","delta":1}'

Use counter shards

A counter with shards spreads heavy traffic over several rows. Morphic adds the rows together when it reads the counter.

  1. On the Key-value page, select Namespace settings.
  2. In Counter shards, enter a number from 1 to 64.

A sharded namespace accepts only numeric values.