Why do batch operations reduce the number of network round trips in REST APIs?
Think about how sending many small packages compares to sending one big package.
Batch operations group multiple requests into a single network call, which means fewer trips back and forth between client and server. This reduces latency and overhead.
Consider this Python code simulating batch vs single requests. What is the output?
import time def single_requests(n): total_time = 0 for _ in range(n): time.sleep(0.1) # simulate network delay total_time += 0.1 return total_time def batch_request(n): time.sleep(0.1) # simulate one batch delay return 0.1 print(f"Single requests total time: {single_requests(5)} seconds") print(f"Batch request total time: {batch_request(5)} seconds")
Each single request waits 0.1 seconds, batch waits once.
Five single requests each wait 0.1 seconds, totaling 0.5 seconds. The batch request waits only once for 0.1 seconds.
Given this JavaScript code simulating batch API calls, what is logged?
async function simulateBatch() { const delay = ms => new Promise(res => setTimeout(res, ms)); async function singleCall(id) { await delay(100); return `Response ${id}`; } async function batchCall(ids) { await delay(100); return ids.map(id => `Response ${id}`); } const singleResults = []; for (let i = 1; i <= 3; i++) { singleResults.push(await singleCall(i)); } const batchResults = await batchCall([1, 2, 3]); console.log(singleResults); console.log(batchResults); } simulateBatch();
Both single and batch calls return arrays of responses for ids 1 to 3.
The single calls collect responses one by one into an array. The batch call returns an array of all responses at once. Both arrays contain the same three responses.
Besides reducing the number of network round trips, what is another key reason batch operations improve API efficiency?
Think about how handling many requests at once can save work on the server side.
Batch operations let the server process multiple requests in one go, reducing repeated setup and teardown work, which saves resources and time.
You have 10 API calls. Each call takes 50ms network latency plus 100ms server processing. If you batch all calls into one request, the network latency is 50ms once and server processing is 100ms times 10 calls. What is the total time difference between batching and sending calls individually?
Calculate total time for individual calls: (latency + processing) * number of calls. For batch: latency once + processing for all calls.
Individual calls: (50ms + 100ms) * 10 = 1500ms. Batch call: 50ms + (100ms * 10) = 1050ms. Difference is 450ms saved by batching.