Bird
Raised Fist0
Rest APIprogramming~20 mins

Idempotency keys for safe retries in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Idempotency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output when retrying a POST request with the same idempotency key?

Consider a REST API that uses idempotency keys to prevent duplicate resource creation. The client sends a POST request with an idempotency key header. The server stores the response for that key.

What will the server return if the client retries the same POST request with the same idempotency key?

Rest API
POST /orders HTTP/1.1
Idempotency-Key: abc123
{
  "item": "book",
  "quantity": 1
}

# Retry with the same Idempotency-Key: abc123
AThe server ignores the idempotency key and processes the request normally.
BThe server creates a new order again and returns a new order ID.
CThe server returns an error indicating the idempotency key is already used.
DThe server returns the original response for the first request without creating a new order.
Attempts:
2 left
💡 Hint

Think about why idempotency keys are used in APIs.

🧠 Conceptual
intermediate
1:30remaining
Why are idempotency keys important in REST APIs?

Which of the following best explains the main purpose of idempotency keys in REST APIs?

ATo allow safe retries of requests without creating duplicate effects.
BTo encrypt the request payload for security.
CTo speed up the server response time by caching.
DTo authenticate the client making the request.
Attempts:
2 left
💡 Hint

Think about what happens when a client retries a request due to network issues.

🔧 Debug
advanced
2:30remaining
Identify the bug in this idempotency key handling code snippet

Review the following pseudocode for handling POST requests with idempotency keys. What is the bug?

Rest API
def handle_post(request):
    key = request.headers.get('Idempotency-Key')
    if key in cache:
        return cache[key]
    response = process_request(request)
    # Missing cache storage here
    return response
AThe code does not check if the idempotency key is missing.
BThe response is not stored in the cache after processing the request.
CThe cache lookup should happen after processing the request.
DThe code should delete the key from cache after returning the response.
Attempts:
2 left
💡 Hint

Think about what happens on the second request with the same key.

📝 Syntax
advanced
2:00remaining
Which option correctly implements idempotency key storage in Python?

Choose the code snippet that correctly stores and returns a cached response for an idempotency key.

Rest API
cache = {}

def handle_request(request):
    key = request.headers.get('Idempotency-Key')
    if key in cache:
        return cache[key]
    response = process(request)
    # Store response here
    return response
A
cache[key] <- response
return response
B
cache[key] == response
return response
C
cache[key] = response
return response
D
cache.add(key, response)
return response
Attempts:
2 left
💡 Hint

Remember how to assign values to dictionary keys in Python.

🚀 Application
expert
3:00remaining
How many unique responses are stored after these requests with idempotency keys?

A client sends these POST requests to the server with idempotency keys:

  1. POST with key 'x1'
  2. POST with key 'x2'
  3. POST with key 'x1' again (retry)
  4. POST with key 'x3'
  5. POST with key 'x2' again (retry)

Assuming the server correctly caches responses by idempotency key, how many unique responses are stored in the cache after these requests?

A3
B5
C2
D4
Attempts:
2 left
💡 Hint

Count unique keys used in the requests.

Practice

(1/5)
1. What is the main purpose of using an idempotency key in REST APIs?
easy
A. To speed up the server response time
B. To prevent duplicate processing of the same request
C. To encrypt the request data
D. To authenticate the user

Solution

  1. Step 1: Understand idempotency key concept

    An idempotency key is a unique identifier sent with a request to ensure the server processes it only once.
  2. Step 2: Identify the main purpose

    This prevents duplicate actions like double payments or repeated orders if the client retries the request.
  3. Final Answer:

    To prevent duplicate processing of the same request -> Option B
  4. Quick Check:

    Idempotency key = prevent duplicates [OK]
Hint: Idempotency keys stop repeated actions safely [OK]
Common Mistakes:
  • Confusing idempotency key with authentication token
  • Thinking it speeds up response time
  • Assuming it encrypts data
2. Which HTTP header is commonly used to send an idempotency key in a REST API request?
easy
A. Idempotency-Key
B. Cache-Control
C. Content-Type
D. Authorization

Solution

  1. Step 1: Recall standard header for idempotency

    The standard practice is to send the unique idempotency key in the Idempotency-Key HTTP header.
  2. Step 2: Differentiate from other headers

    Authorization is for credentials, Content-Type defines data format, and Cache-Control manages caching.
  3. Final Answer:

    Idempotency-Key -> Option A
  4. Quick Check:

    Idempotency key header = Idempotency-Key [OK]
Hint: Idempotency keys go in Idempotency-Key header [OK]
Common Mistakes:
  • Using Authorization header for idempotency key
  • Confusing Content-Type with idempotency key
  • Sending key in request body instead of header
3. Consider this simplified server logic for handling POST requests with idempotency keys:
stored_keys = {}

def handle_request(idempotency_key, data):
    if idempotency_key in stored_keys:
        return stored_keys[idempotency_key]
    response = process_data(data)
    stored_keys[idempotency_key] = response
    return response

# Client sends:
print(handle_request('abc123', 'order1'))
print(handle_request('abc123', 'order1'))
print(handle_request('xyz789', 'order2'))
What will be the output?
medium
A. None, None, None
B. process_data output for order1, None, process_data output for order2
C. process_data output for order1, process_data output for order2, process_data output for order2
D. process_data output for order1, process_data output for order1, process_data output for order2

Solution

  1. Step 1: Analyze first call with key 'abc123'

    Key not in stored_keys, so process_data('order1') runs, result saved and returned.
  2. Step 2: Analyze second call with same key 'abc123'

    Key found, stored response returned without reprocessing.
  3. Step 3: Analyze third call with new key 'xyz789'

    Key not found, process_data('order2') runs, result saved and returned.
  4. Final Answer:

    process_data output for order1, process_data output for order1, process_data output for order2 -> Option D
  5. Quick Check:

    Repeated key returns cached response [OK]
Hint: Repeated keys return cached response, new keys process data [OK]
Common Mistakes:
  • Assuming second call reprocesses data
  • Confusing keys and responses
  • Thinking None is returned on repeats
4. A developer wrote this code snippet to handle idempotent POST requests:
cache = {}
def post_request(key, data):
    if key not in cache:
        process(data)
    return cache[key]
What is the bug in this code?
medium
A. It never stores the processed result in cache
B. It processes data twice for the same key
C. It raises an error if key is missing
D. It uses the wrong HTTP method

Solution

  1. Step 1: Check caching logic

    The code checks if key not in cache, then calls process(data), but never saves the result in cache.
  2. Step 2: Identify consequence

    Since cache[key] is never set, returning cache[key] will cause a KeyError or return None incorrectly.
  3. Final Answer:

    It never stores the processed result in cache -> Option A
  4. Quick Check:

    Missing cache storage causes errors [OK]
Hint: Always save processed result in cache before returning [OK]
Common Mistakes:
  • Assuming process(data) stores result automatically
  • Ignoring missing cache assignment
  • Thinking HTTP method affects caching here
5. You are designing a payment API that uses idempotency keys to avoid duplicate charges. Which approach best ensures safe retries without charging twice if the client resends the same request due to a timeout?
hard
A. Ignore the idempotency key and process every request independently
B. Reject any request with an idempotency key that was seen before
C. Store the payment result linked to the idempotency key and return it on repeated requests
D. Process the payment again but log a warning for duplicate keys

Solution

  1. Step 1: Understand safe retry requirements

    Safe retries mean the client can resend the same request without causing duplicate charges.
  2. Step 2: Evaluate options

    Store the payment result linked to the idempotency key and return it on repeated requests stores the payment result linked to the key and returns it on repeats, preventing double charges. Ignore the idempotency key and process every request independently processes every request, risking duplicates. Reject any request with an idempotency key that was seen before rejects repeats, which may cause client errors. Process the payment again but log a warning for duplicate keys processes again, causing duplicates.
  3. Final Answer:

    Store the payment result linked to the idempotency key and return it on repeated requests -> Option C
  4. Quick Check:

    Store and reuse result for idempotency [OK]
Hint: Save and reuse payment result by key to avoid duplicates [OK]
Common Mistakes:
  • Rejecting repeated keys causing client errors
  • Processing duplicates causing double charges
  • Logging warnings but still charging twice
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