Bird
Raised Fist0
Rest APIprogramming~10 mins

Expiration-based caching in Rest API - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Expiration-based caching
Request received
↓
Check cache for data
↓
Check if [Fetch fresh data
↓
Store data in cache with expiration
↓
Return cached data
↓
Send response
When a request comes, the system checks the cache. If data is there and not expired, it returns cached data. Otherwise, it fetches fresh data, stores it with an expiration time, then returns it.
Execution Sample
Rest API
cache = {}

# On request
key = 'user_123'
now = 100

if key in cache and cache[key]['expiry'] > now:
    data = cache[key]['data']
else:
    data = 'fresh_data'
    cache[key] = {'data': data, 'expiry': now + 10}
This code checks if cached data for 'user_123' exists and is not expired at time 100; if expired or missing, it fetches fresh data and caches it with expiry 110.
Execution Table
StepActionCache StateConditionResult
1Check if 'user_123' in cache{}FalseGo to fetch fresh data
2Fetch fresh data{}N/Adata = 'fresh_data'
3Store data with expiry 110{'user_123': {'data': 'fresh_data', 'expiry': 110}}N/ACache updated
4Return data{'user_123': {'data': 'fresh_data', 'expiry': 110}}N/AReturn 'fresh_data'
5Next request at time 105{'user_123': {'data': 'fresh_data', 'expiry': 110}}'expiry' > now (110 > 105)Return cached data
6Next request at time 115{'user_123': {'data': 'fresh_data', 'expiry': 110}}'expiry' > now (110 > 115) is FalseFetch fresh data again
💡 Cache returns fresh data if expired or missing; otherwise returns cached data.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5After Step 6
cache{}{}{'user_123': {'data': 'fresh_data', 'expiry': 110}}{'user_123': {'data': 'fresh_data', 'expiry': 110}}{'user_123': {'data': 'fresh_data', 'expiry': 125}}
dataN/AN/A'fresh_data''fresh_data''fresh_data'
now100100100105115
Key Moments - 3 Insights
Why do we check if the cache entry's expiry time is greater than the current time?
Because even if data is in cache, it might be old. Checking expiry ensures we only use fresh cached data. See execution_table step 5 and 6 where expiry time decides if cache is valid.
What happens if the cache is empty when a request comes in?
The code fetches fresh data and stores it with an expiry time. This is shown in execution_table step 1 (cache miss) leading to step 2 and 3.
Why do we update the cache with a new expiry time after fetching fresh data?
To make sure future requests use this fresh data until it expires. Without updating expiry, cache would never refresh. See execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5. What is the condition checked to decide if cached data is used?
A'expiry' == now (110 == 105)
B'expiry' > now (110 > 105)
C'expiry' < now (110 < 105)
DCache is empty
💡 Hint
Check the 'Condition' column in execution_table row for step 5.
At which step does the cache get updated with fresh data and expiry?
AStep 3
BStep 1
CStep 5
DStep 6
💡 Hint
Look at the 'Action' and 'Cache State' columns in execution_table for when cache changes.
If the current time 'now' was 108 at step 5, what would happen?
AFresh data is fetched again
BCache is cleared
CCache data is returned
DError occurs
💡 Hint
Refer to variable_tracker for 'now' and cache expiry comparison logic.
Concept Snapshot
Expiration-based caching:
- Store data with an expiry timestamp
- On request, check if cached data exists and expiry > current time
- If valid, return cached data
- If expired or missing, fetch fresh data and update cache
- Helps reduce repeated data fetching and keeps data fresh
Full Transcript
Expiration-based caching means saving data temporarily with a time limit. When a request comes, the system looks in the cache. If data is there and not expired, it returns that data quickly. If data is missing or expired, it fetches new data, saves it with a new expiry time, and returns it. This way, the system avoids fetching data too often but still keeps it fresh. The example code shows checking the cache, comparing expiry times, and updating the cache when needed. The execution table walks through these steps, showing when cached data is used or refreshed.

Practice

(1/5)
1. What does the Cache-Control: max-age header do in expiration-based caching?
easy
A. It deletes the cache immediately after the response.
B. It disables caching for the resource.
C. It sets how long the cached data is considered fresh.
D. It forces the client to always fetch new data.

Solution

  1. Step 1: Understand the role of Cache-Control header

    The Cache-Control header controls caching behavior for HTTP responses.
  2. Step 2: Identify the meaning of max-age directive

    The max-age directive specifies the time in seconds that the response is considered fresh and can be served from cache.
  3. Final Answer:

    It sets how long the cached data is considered fresh. -> Option C
  4. Quick Check:

    max-age = cache freshness duration [OK]
Hint: Remember max-age sets cache freshness time in seconds [OK]
Common Mistakes:
  • Confusing max-age with disabling cache
  • Thinking max-age deletes cache immediately
  • Assuming max-age forces fresh fetch every time
2. Which of the following is the correct syntax to set a cache expiration of 300 seconds in an HTTP response header?
easy
A. Cache-Control: maxage: 300
B. Cache-Control: max-age=300
C. Cache-Control: expire=300
D. Cache-Control: timeout=300

Solution

  1. Step 1: Recall correct Cache-Control syntax

    The Cache-Control header uses directives separated by commas, with max-age specified as max-age=seconds.
  2. Step 2: Compare options to correct syntax

    Only Cache-Control: max-age=300 uses the correct format: max-age=300.
  3. Final Answer:

    Cache-Control: max-age=300 -> Option B
  4. Quick Check:

    Correct header syntax = max-age=seconds [OK]
Hint: Use equal sign (=) with max-age, no spaces [OK]
Common Mistakes:
  • Using colon instead of equal sign
  • Using incorrect directive names like expire or timeout
  • Adding spaces inside the directive
3. Given this HTTP response header:
Cache-Control: max-age=10
What will happen if a client requests the same resource 5 seconds later?
medium
A. The client will use the cached response without contacting the server.
B. The client will ignore the cache and fetch new data from the server.
C. The client will receive a 404 error.
D. The client will refresh the cache but still use old data.

Solution

  1. Step 1: Understand max-age meaning

    max-age=10 means the cached data is fresh for 10 seconds after the first fetch.
  2. Step 2: Check time elapsed since caching

    5 seconds is less than 10 seconds, so cache is still fresh and valid.
  3. Final Answer:

    The client will use the cached response without contacting the server. -> Option A
  4. Quick Check:

    Elapsed time < max-age = use cache [OK]
Hint: If request time < max-age, cache is used [OK]
Common Mistakes:
  • Assuming cache expires immediately
  • Thinking client always fetches new data
  • Confusing max-age with cache invalidation
4. You set Cache-Control: max-age=60 but clients still fetch new data every time. What is the likely mistake?
medium
A. The client does not support caching headers.
B. The max-age value should be in milliseconds, not seconds.
C. The resource URL is missing a file extension.
D. The server is sending no-cache header overriding max-age.

Solution

  1. Step 1: Check for conflicting headers

    If the server sends a no-cache directive, it forces clients to revalidate or fetch fresh data despite max-age.
  2. Step 2: Understand max-age units and client support

    max-age is in seconds, and most clients support caching headers, so these are unlikely causes.
  3. Final Answer:

    The server is sending no-cache header overriding max-age. -> Option D
  4. Quick Check:

    no-cache overrides max-age [OK]
Hint: Check for no-cache header overriding max-age [OK]
Common Mistakes:
  • Confusing seconds with milliseconds for max-age
  • Blaming client support without checking headers
  • Assuming URL format affects caching
5. You want to cache API responses for 5 minutes but ensure clients always get fresh data after expiration. Which header setup is best?
hard
A. Cache-Control: max-age=300, must-revalidate
B. Cache-Control: max-age=300, no-store
C. Cache-Control: no-cache, max-age=300
D. Cache-Control: max-age=0, public

Solution

  1. Step 1: Understand caching for 5 minutes

    max-age=300 sets cache freshness for 300 seconds (5 minutes).
  2. Step 2: Ensure fresh data after expiration

    must-revalidate forces clients to check with server after max-age expires before using cached data.
  3. Step 3: Evaluate other options

    no-store disables caching, no-cache forces revalidation every time, max-age=0 means no caching.
  4. Final Answer:

    Cache-Control: max-age=300, must-revalidate -> Option A
  5. Quick Check:

    max-age + must-revalidate = cache then fresh after expiry [OK]
Hint: Use must-revalidate with max-age for fresh data after expiry [OK]
Common Mistakes:
  • Using no-store disables caching completely
  • Using no-cache forces revalidation every request
  • Setting max-age=0 disables caching
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard