Bird
Raised Fist0
Rest APIprogramming~20 mins

Async batch processing in Rest API - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Async Batch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this async batch processing code?

Consider a REST API that processes a batch of tasks asynchronously. The server returns a job ID immediately, and the client polls the job status until completion.

What will be printed by the client code below?

Rest API
import asyncio

async def check_status(job_id):
    # Simulate job completion after 3 checks
    for i in range(3):
        print(f"Checking status for job {job_id}, attempt {i+1}")
        await asyncio.sleep(0.1)
    return "completed"

async def main():
    job_id = "job123"
    status = await check_status(job_id)
    print(f"Job {job_id} status: {status}")

asyncio.run(main())
A
Checking status for job job123, attempt 1
Checking status for job job123, attempt 2
Job job123 status: completed
Checking status for job job123, attempt 3
B
Job job123 status: completed
Checking status for job job123, attempt 1
Checking status for job job123, attempt 2
Checking status for job job123, attempt 3
C
Checking status for job job123, attempt 1
Job job123 status: completed
Checking status for job job123, attempt 2
Checking status for job job123, attempt 3
D
Checking status for job job123, attempt 1
Checking status for job job123, attempt 2
Checking status for job job123, attempt 3
Job job123 status: completed
Attempts:
2 left
💡 Hint

Remember that await pauses the function until the awaited coroutine finishes.

🧠 Conceptual
intermediate
1:00remaining
Which HTTP method is best for submitting an async batch job to a REST API?

You want to send a batch of tasks to a REST API that will process them asynchronously. Which HTTP method should you use to submit the batch job?

APOST
BGET
CPUT
DDELETE
Attempts:
2 left
💡 Hint

Think about which method is used to create new resources or submit data.

🔧 Debug
advanced
2:30remaining
Why does this async batch polling code never stop?

Look at this client code that polls a batch job status from a REST API. It never stops polling. Why?

Rest API
import asyncio
import random

async def get_status(job_id):
    # Simulate random job status
    return random.choice(["pending", "pending", "completed"])

async def poll_job(job_id):
    status = "pending"
    while status != "completed":
        status = await get_status(job_id)
        print(f"Job {job_id} status: {status}")
        await asyncio.sleep(0.1)

asyncio.run(poll_job("job456"))
AThe code is missing a break statement inside the loop.
BThe random choice includes "pending" twice, so it might never pick "completed".
CThe await asyncio.sleep(0.1) is too short to allow status update.
DThe function get_status is not awaited properly.
Attempts:
2 left
💡 Hint

Look at the probabilities of the status values returned.

📝 Syntax
advanced
1:30remaining
Which option correctly defines an async function to submit a batch job and return job ID?

Choose the correct Python async function syntax that submits a batch job and returns a job ID string.

A
async def submit_batch():
    job_id = "job789"
    yield job_id
B
def async submit_batch():
    job_id = "job789"
    return job_id
C
async def submit_batch():
    job_id = "job789"
    return job_id
D
async submit_batch() -> str:
    job_id = "job789"
    return job_id
Attempts:
2 left
💡 Hint

Remember the correct order of keywords for async function definitions.

🚀 Application
expert
2:00remaining
How many items will be in the batch result after processing this async batch?

This code submits a batch of 5 tasks asynchronously and collects results. How many items will be in the results list after completion?

Rest API
import asyncio

async def process_task(task_id):
    await asyncio.sleep(0.1)
    return f"result_{task_id}"

async def process_batch(tasks):
    results = []
    for task in tasks:
        result = await process_task(task)
        results.append(result)
    return results

batch_tasks = [1, 2, 3, 4, 5]
results = asyncio.run(process_batch(batch_tasks))
print(len(results))
A5
B0
C1
DRaises an exception
Attempts:
2 left
💡 Hint

Each task is awaited and its result appended to the list.

Practice

(1/5)
1. What is the main benefit of using async batch processing in REST APIs?
easy
A. It allows sending multiple requests at once to save time.
B. It makes each request slower but more secure.
C. It processes requests one by one to avoid errors.
D. It disables parallel processing to reduce server load.

Solution

  1. Step 1: Understand async batch processing purpose

    Async batch processing sends many requests together instead of one at a time.
  2. Step 2: Identify the benefit

    Sending requests together saves time and improves efficiency.
  3. Final Answer:

    It allows sending multiple requests at once to save time. -> Option A
  4. Quick Check:

    Async batch processing = multiple requests at once [OK]
Hint: Async batch sends many requests together to save time [OK]
Common Mistakes:
  • Thinking async batch slows down requests
  • Believing requests are processed one by one
  • Confusing async batch with disabling parallelism
2. Which of the following is the correct way to start an async batch request in JavaScript using fetch?
easy
A. fetch('/batch', { method: 'GET', body: requests })
B. fetch('/batch', 'POST', requests)
C. fetch('/batch', { method: 'POST', body: JSON.stringify(requests) })
D. fetch('/batch', { method: 'POST', body: requests })

Solution

  1. Step 1: Check fetch syntax for POST with JSON body

    fetch requires method and body as JSON string for POST requests.
  2. Step 2: Identify correct option

    fetch('/batch', { method: 'POST', body: JSON.stringify(requests) }) uses method 'POST' and JSON.stringify to convert requests to string.
  3. Final Answer:

    fetch('/batch', { method: 'POST', body: JSON.stringify(requests) }) -> Option C
  4. Quick Check:

    fetch POST with JSON body = fetch('/batch', { method: 'POST', body: JSON.stringify(requests) }) [OK]
Hint: Use JSON.stringify for POST body in fetch [OK]
Common Mistakes:
  • Passing body without JSON.stringify
  • Using GET method with body
  • Wrong fetch parameter order
3. Given this async batch code snippet, what will be the output?
const batchRequests = [
  fetch('/api/data1'),
  fetch('/api/data2'),
  fetch('/api/data3')
];

Promise.all(batchRequests)
  .then(responses => responses.map(r => r.status))
  .then(statuses => console.log(statuses));
medium
A. [Promise, Promise, Promise]
B. [200, 200, 200]
C. [undefined, undefined, undefined]
D. Error: Cannot read property 'status' of undefined

Solution

  1. Step 1: Understand Promise.all with fetch

    Promise.all waits for all fetch requests to complete and returns an array of responses.
  2. Step 2: Map responses to their status codes

    Each response has a status property, usually 200 if successful.
  3. Final Answer:

    [200, 200, 200] -> Option B
  4. Quick Check:

    Promise.all fetch statuses = [200, 200, 200] [OK]
Hint: Promise.all returns array of resolved values [OK]
Common Mistakes:
  • Expecting promises instead of resolved responses
  • Trying to access status before Promise.all resolves
  • Confusing map on promises vs responses
4. Identify the error in this async batch processing code snippet:
async function batchFetch(urls) {
  const results = [];
  urls.forEach(async url => {
    const res = await fetch(url);
    results.push(await res.json());
  });
  return results;
}
medium
A. Using forEach with async does not wait for all fetches to finish.
B. Missing JSON.stringify on fetch body.
C. results array is declared inside the loop.
D. fetch should not be awaited inside async function.

Solution

  1. Step 1: Analyze async inside forEach

    forEach does not wait for async callbacks, so results may be empty on return.
  2. Step 2: Identify correct fix

    Use for...of loop with await or Promise.all to wait for all fetches.
  3. Final Answer:

    Using forEach with async does not wait for all fetches to finish. -> Option A
  4. Quick Check:

    forEach async does not await = Using forEach with async does not wait for all fetches to finish. [OK]
Hint: Avoid async inside forEach; use for...of or Promise.all [OK]
Common Mistakes:
  • Assuming forEach waits for async callbacks
  • Not returning or awaiting promises properly
  • Misplacing results array declaration
5. You want to send 100 API requests in batches of 10 asynchronously to avoid overloading the server. Which approach correctly implements this in JavaScript?
hard
A. Send requests one by one using a for loop with await inside.
B. Send all 100 requests at once with Promise.all without batching.
C. Use a forEach loop with async fetch calls without awaiting.
D. Split URLs into chunks of 10, then use Promise.all on each chunk sequentially.

Solution

  1. Step 1: Understand batch size control

    Sending all 100 requests at once may overload the server; batching limits concurrency.
  2. Step 2: Implement batch processing

    Split URLs into groups of 10, then await Promise.all for each batch sequentially.
  3. Final Answer:

    Split URLs into chunks of 10, then use Promise.all on each chunk sequentially. -> Option D
  4. Quick Check:

    Batch requests in chunks with Promise.all = Split URLs into chunks of 10, then use Promise.all on each chunk sequentially. [OK]
Hint: Batch requests in small groups, await each batch [OK]
Common Mistakes:
  • Sending all requests at once causing overload
  • Not awaiting async calls properly
  • Sending requests one by one losing async benefits
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