Typorithm · medium

Cache-Aside

redis-cache-asiderediscacheexpirettl
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Cache-Aside

0%

Patterns

Cache-aside has the app read the cache with GET first; on a miss it loads from the database and writes back with SET ... EX so the entry carries a TTL. EXPIRE refreshes the TTL, and DEL invalidates the key on writes.

In the cache-aside (lazy-loading) pattern the application owns the cache. Every read does a GET first; a hit returns immediately, a miss falls through to the database, and the app then SETs the value with an EX expiry so the entry is bounded.

EXPIRE sets or refreshes the TTL on a key that already exists, and TTL reports the seconds remaining. A TTL caps how stale cached data can get, because the entry self-destructs once the timer runs out.

When the underlying record changes, the app issues DEL to invalidate the cached copy. The next read then misses and repopulates the cache with fresh data, keeping the cache consistent with the source of truth.

01

Read path: GET, then SET ... EX on a miss.

02

EXPIRE refreshes the TTL; TTL bounds staleness.

03

DEL invalidates a key after a database write.

GET cache:user:1
SET cache:user:1 "{name:Ada}" EX 300
EXPIRE cache:user:1 300
TTL cache:user:1
DEL cache:user:1

Read the implementation

Connect each part of the code to the concept before you type.

1. Read the cache first

Cache-aside starts with a GET; the app checks the cache before touching the database.

GET cache:user:1

2. Populate on miss

On a miss the app loads from the database and SETs the value with EX to give it a TTL.

SET cache:user:1 "{name:Ada}" EX 300

3. Refresh the TTL

EXPIRE sets or refreshes the time-to-live on a key that already exists.

EXPIRE cache:user:1 300

4. Inspect remaining life

TTL reports the seconds left before the key expires, bounding how stale data can be.

TTL cache:user:1

5. Invalidate on write

DEL removes the cached entry so the next read repopulates it after a database write.

DEL cache:user:1

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Cache-Aside: Lesson & Practice · Typorithm | ApplyDjinn