Thuta Learning
Redis
BasicData & Databasesbeginner

Strings, Counters, EXPIRE, and TTL

What you'll walk away with

  • Explain the core ideas behind Strings, Counters, EXPIRE, and TTL
  • Run the sample Redis command or code and verify its output
  • Apply the technique correctly to the Tutorial Platform and production scenarios

Build the mental model

Strings store text, numbers, or binary bytes. `INCR` provides an atomic counter across concurrent clients, while `SET ... NX/XX EX/PX` combines conditional writes and expiry in one command. A plain replacement SET can remove an existing TTL, so use `KEEPTTL` or an explicit expiry policy.

Connect it to a real scenario

Use `INCR` for page views, `SET ... EX 600 NX` for an email-verification code, and a JSON string with TTL for a catalog fragment. Applications must distinguish TTL results `-1` (no expiry) and `-2` (missing key).

Try the working example

shell
INCR metrics:tutorial:42:views
SET verify:email:user:42 834921 EX 600 NX
GET verify:email:user:42
TTL verify:email:user:42
SET tutorial:42:card '{"title":"Redis"}' EX 300
GET tutorial:42:card
You should see
You create an atomic counter, an expiring verification code, and a five-minute cache entry.

5-minute try-it

Implement a download counter, a one-time idempotency key, and a 30-second API response cache.

One important caution

If a process crashes between INCR and EXPIRE, an immortal key can remain. Use a transaction or script when the pair must be atomic.

Redis — StringsRedis

Easy traps

  • If a process crashes between INCR and EXPIRE, an immortal key can remain. Use a transaction or script when the pair must be atomic.
  • Validate sample commands on a local or test instance with recoverable data before applying them to production Redis.

Exercise

Implement a download counter, a one-time idempotency key, and a 30-second API response cache.

You'll know it worked when: You create an atomic counter, an expiring verification code, and a five-minute cache entry.

Strings, Counters, EXPIRE, and TTL | Thuta Learning