Course outline

Redis / Basic: keys and bounded data structures / Lesson 2

Strings, counters and conditional SET

Use byte strings and atomic integer operations with explicit input and expiry rules. Distinguish a conditional create from a complete distributed-lock or payment protocol.

About 4 min readContent reviewed
On this page

Lesson goals

  • Explain string serialization and integer counter limits.
  • Choose atomic options and interpret conditional outcomes.

A Redis string stores bytes, not an application type declaration

Redis strings can represent text, serialized objects, binary values or numeric text interpreted by specific commands. GET does not know whether the bytes are a price, a token or a JSON object. INCR and related integer operations require valid signed integer values within their supported range. A floating price or malformed counter is not silently a valid integer. Keep monetary arithmetic in a suitable exact representation and authoritative system rather than using floating counters by convenience. Record how clients encode missing values so a missing key is distinguishable from a stored empty string.

Use the server operation for one atomic increment

Assume the synthetic counter is absent. INCR initializes it from zero and returns one; INCRBY adds four and returns five. A separate GET, local addition and SET can lose a concurrent increment, whereas the integer operations perform their own atomic update. These replies are derived from the declared empty fixture and no server is run. The commands do not impose a request idempotency rule: retransmitting an increment as a new operation can increment again even though the business event happened only once.

redis Illustrative absent-key counter sequence
INCR lab:visits
INCRBY lab:visits 4
GET lab:visits
Expected output
1
5
5

Expected results are integer 1, integer 5 and the string representation 5. They assume no other writer or prior key.

Combine value and expiry in one command

SET supports conditional and expiration options with versioned syntax. SET key value NX EX seconds can create a short-lived value only when the key does not exist, avoiding a separate SET-then-EXPIRE gap. NX failure is an ordinary nonapplication result, not automatically a connection failure. A successful conditional set is only a primitive: it does not prove safe distributed mutual exclusion under every failover or lease-expiry scenario. Review ownership tokens, expiry, release checks and downstream fencing before using it for coordination. Never use a fixed shared lock value as a universal lock recipe.

Expose a lost-update schedule without running a service

The local model shows two readers observing ten, each calculating eleven, and the second absolute assignment overwriting the first. It contrasts that with two sequential arithmetic increments yielding twelve. The model is intentionally simple and does not emulate Redis scheduling, persistence or client retries. Its purpose is to make the read-modify-write error visible. Test business-event identity separately when an API can retry; replacing a race with atomic INCR solves concurrent arithmetic, not duplicate event delivery or an uncertain response after a successful write.

python Offline lost-update arithmetic model
initial = 10
a_read = initial
b_read = initial
naive = a_read + 1
naive = b_read + 1
atomic_model = initial
atomic_model += 1
atomic_model += 1
assert naive == 11
assert atomic_model == 12

Both assertions describe the chosen schedule only. They neither connect to Redis nor prove a complete concurrency or retry protocol.

Know which write changes the existing TTL

Ordinary SET replaces the string value and normally removes an existing key expiry unless appropriate retention options are used. In-place changes such as INCR have different expiry behavior, so do not assume every mutation resets or preserves TTL identically. SET KEEPTTL is available from Redis 6.0 and must be chosen deliberately. Redis 8.4 adds newer value-comparison options and compare-delete capability; they are outside this course’s 8.2 baseline. Verify deployed support rather than copying a newer command form into an older or restricted managed endpoint.

Common errors and fixes

ERR value is not an integer or out of range

Why it happens
The stored bytes or result do not satisfy the integer command’s contract.
How to fix it
Inspect the key owner and serializer; correct malformed input under the data policy.
Prevent it next time
Validate counter types and boundary values before writes.

A counter loses concurrent events

Why it happens
The application used GET followed by absolute SET.
How to fix it
Use an appropriate atomic operation or reviewed compare-and-set protocol.
Prevent it next time
Test overlapping updates and distinguish them from duplicate retries.

A refreshed value unexpectedly becomes persistent

Why it happens
A plain SET cleared an earlier TTL.
How to fix it
Apply the intended expiry atomically or choose supported KEEPTTL deliberately.
Prevent it next time
Include TTL behavior in every key-family write contract.

Check your understanding

1. Two clients each increment the same valid integer key. Why is INCR preferable to reading and storing a computed value?

Show worked solution

INCR performs the arithmetic as one server operation, avoiding a stale absolute assignment overwriting the other increment. A separate read-modify-write requires coordination. Still identify repeated business requests: two newly submitted increments can both succeed even if they represent the same payment or visit event, so atomicity and idempotency remain distinct.

2. A short-lived token value is rewritten with plain SET. What should a test verify?

Show worked solution

Verify whether the key now has the intended expiry, because plain SET can remove the previous TTL. Prefer one write containing the desired value and expiration, or a supported explicit retention option when retaining the old deadline is correct. A correct token payload does not establish a correct validity window.

Key takeaways

  • Atomic arithmetic avoids lost updates but does not deduplicate business events.
  • Conditional SET and TTL options are explicit versioned primitives.

Official references