Bird
Raised Fist0
FastAPIframework~20 mins

Caching strategies in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
FastAPI Caching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this FastAPI endpoint with cache?

Consider this FastAPI endpoint using a simple in-memory cache dictionary. What will be the response when calling /data twice?

FastAPI
from fastapi import FastAPI
app = FastAPI()
cache = {}

@app.get('/data')
async def get_data():
    if 'value' in cache:
        return {'data': cache['value']}
    cache['value'] = 'cached result'
    return {'data': 'cached result'}
A500 Internal Server Error on both calls
B{"data": "cached result"} on first call, then same on second call
C{"data": null} on first call, then {"data": "cached result"} on second call
D{"data": "cached result"} on first call, then KeyError on second call
Attempts:
2 left
💡 Hint

Think about how the cache dictionary stores and returns the value.

📝 Syntax
intermediate
2:00remaining
Which option correctly uses FastAPI's Depends for caching?

FastAPI allows dependency injection for caching. Which code snippet correctly uses Depends to inject a cache dependency?

A
from fastapi import Depends
cache = {}
async def get_cache():
    return cache

@app.get('/item')
async def read_item(cache=Depends(get_cache)):
    return {'cache_size': len(cache)}
B
from fastapi import Depends
cache = {}
async def get_cache():
    return cache

@app.get('/item')
async def read_item(cache=get_cache()):
    return {'cache_size': len(cache)}
C
from fastapi import Depends
cache = {}
async def get_cache():
    return cache

@app.get('/item')
async def read_item(cache=Depends(get_cache())):
    return {'cache_size': len(cache)}
D
from fastapi import Depends
cache = {}
async def get_cache():
    return cache

@app.get('/item')
async def read_item(cache=Depends):
    return {'cache_size': len(cache)}
Attempts:
2 left
💡 Hint

Remember that Depends takes a callable without calling it.

🔧 Debug
advanced
2:00remaining
Why does this FastAPI cache implementation cause stale data?

Given this code snippet, why might the cache return outdated data?

FastAPI
from fastapi import FastAPI
app = FastAPI()
cache = {'data': 'old'}

@app.get('/update')
async def update_data():
    cache['data'] = 'new'
    return {'status': 'updated'}

@app.get('/data')
async def get_data():
    return {'data': cache['data']}
ABecause the cache dictionary is global and shared, updates affect all requests immediately, so no stale data occurs
BBecause the cache is not thread-safe, concurrent requests may see stale or inconsistent data
CBecause the cache is updated only on /update, if /data is called before /update, it returns old data
DBecause FastAPI automatically clears cache dictionaries after each request, causing stale data
Attempts:
2 left
💡 Hint

Think about when the cache value changes and when it is read.

🧠 Conceptual
advanced
2:00remaining
Which caching strategy best fits FastAPI for data that changes every minute?

You have an API endpoint that returns data updated every minute. Which caching strategy is best to reduce load but keep data fresh?

AUse client-side caching only, relying on browser cache headers
BUse no caching to always return fresh data, ignoring performance
CUse a cache that never expires and manually clear it when data changes
DUse in-memory cache with a time-to-live (TTL) of 60 seconds to expire cached data automatically
Attempts:
2 left
💡 Hint

Think about balancing freshness and performance with automatic expiration.

❓ state_output
expert
2:00remaining
What is the output after these FastAPI cache updates?

Given this FastAPI app, what is the output of calling /get after calling /set/5 and then /set/10?

FastAPI
from fastapi import FastAPI
app = FastAPI()
cache = {}

@app.get('/set/{value}')
async def set_value(value: int):
    cache['num'] = value
    return {'status': 'set', 'value': value}

@app.get('/get')
async def get_value():
    return {'num': cache.get('num', 0)}
A{"num": 10}
B{"num": 5}
C{"num": 0}
DKeyError exception
Attempts:
2 left
💡 Hint

Consider the order of calls and how the cache dictionary updates.

Practice

(1/5)
1. What is the main purpose of using caching in a FastAPI application?
easy
A. To increase the size of the application code
B. To remove all data from the server
C. To make the app slower for testing
D. To save repeated work and speed up response times

Solution

  1. Step 1: Understand caching concept

    Caching stores results of expensive operations to reuse later.
  2. Step 2: Identify caching benefit in FastAPI

    This reuse saves repeated work and speeds up response times.
  3. Final Answer:

    To save repeated work and speed up response times -> Option D
  4. Quick Check:

    Caching purpose = speed up responses [OK]
Hint: Caching means saving work to respond faster [OK]
Common Mistakes:
  • Thinking caching increases code size
  • Believing caching slows down the app
  • Confusing caching with deleting data
2. Which of the following is the correct way to apply caching with expiration in FastAPI using the decorator?
easy
A. @cache(expire=60)
B. @cache_time(60)
C. @cache(expiration=60)
D. @cache(60_seconds)

Solution

  1. Step 1: Recall FastAPI cache decorator syntax

    The correct decorator is @cache(expire=seconds) to set expiration time.
  2. Step 2: Match options with correct syntax

    Only @cache(expire=60) matches the correct pattern.
  3. Final Answer:

    @cache(expire=60) -> Option A
  4. Quick Check:

    Decorator with expire=60 is correct [OK]
Hint: Use @cache with expire=seconds for expiration [OK]
Common Mistakes:
  • Using wrong decorator names like @cache_time
  • Using incorrect parameter names like expiration
  • Passing expiration time without parameter name
3. Given this FastAPI code snippet, what will be the output on the second call to /data within 10 seconds?
from fastapi import FastAPI
from fastapi_cache.decorator import cache

app = FastAPI()

@cache(expire=10)
async def get_data():
    print('Fetching data')
    return {'value': 42}

@app.get('/data')
async def data():
    return await get_data()
medium
A. {'value': 42} and prints 'Fetching data' once only
B. {'value': 42} and prints 'Fetching data' every call
C. Error because cache decorator is missing setup
D. Empty response because cache expired immediately

Solution

  1. Step 1: Check for cache initialization

    The code uses @cache but lacks FastAPICache.init with a backend on startup.
  2. Step 2: Analyze execution

    Without init, FastAPICache.get raises AttributeError on first call, before executing get_data or printing.
  3. Final Answer:

    Error because cache decorator is missing setup -> Option C
  4. Quick Check:

    Missing FastAPICache.init causes runtime error [OK]
Hint: Cache decorator requires FastAPICache.init on startup [OK]
Common Mistakes:
  • Assuming caching works without FastAPICache.init, print once only
  • Thinking no caching, print every call
  • Believing cache expires immediately
4. Identify the error in this FastAPI caching setup:
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend

app = FastAPI()

@app.on_event('startup')
async def startup():
    FastAPICache.init(InMemoryBackend())

@cache(expire=30)
async def get_info():
    return {'info': 'cached data'}
medium
A. InMemoryBackend requires a Redis URL parameter
B. Cache decorator is used without importing it
C. Missing await keyword when calling FastAPICache.init
D. Startup event should be named 'start' instead of 'startup'

Solution

  1. Step 1: Check imports for cache decorator

    The code uses @cache but does not import it from fastapi_cache.decorator.
  2. Step 2: Verify other parts for correctness

    FastAPICache.init is correctly called; InMemoryBackend needs no parameters; event name 'startup' is correct.
  3. Final Answer:

    Cache decorator is used without importing it -> Option B
  4. Quick Check:

    Missing import of cache decorator causes error [OK]
Hint: Always import @cache decorator before using it [OK]
Common Mistakes:
  • Forgetting to import cache decorator
  • Passing Redis URL to InMemoryBackend
  • Renaming startup event incorrectly
5. You want to cache user profile data in FastAPI using Redis backend with a 5-minute expiration. Which setup correctly initializes caching and applies it to the get_user_profile function?
from fastapi import FastAPI
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
import aioredis

app = FastAPI()

@app.on_event('startup')
async def startup():
    redis = aioredis.from_url('redis://localhost')
    FastAPICache.init(RedisBackend(redis), prefix='fastapi-cache')

@cache(expire=300)
async def get_user_profile(user_id: int):
    # Simulate fetching user profile
    return {'user_id': user_id, 'name': 'Alice'}
hard
A. Correct setup: Redis backend initialized with aioredis, cache decorator with expire=300
B. Incorrect: RedisBackend needs a string URL, not aioredis instance
C. Incorrect: Cache decorator expire should be in milliseconds, not seconds
D. Incorrect: FastAPICache.init must be called inside the cached function

Solution

  1. Step 1: Verify Redis backend initialization

    Using aioredis.from_url and passing RedisBackend(redis) is correct for Redis caching.
  2. Step 2: Check cache decorator usage

    @cache(expire=300) sets 5 minutes expiration correctly in seconds.
  3. Final Answer:

    Correct setup: Redis backend initialized with aioredis, cache decorator with expire=300 -> Option A
  4. Quick Check:

    Redis backend + expire=300 seconds = correct caching [OK]
Hint: Use aioredis instance with RedisBackend and expire in seconds [OK]
Common Mistakes:
  • Passing Redis URL string directly instead of aioredis instance
  • Using expire in milliseconds instead of seconds
  • Calling FastAPICache.init inside cached function
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