CodeBlanks Logo Icon CodeBlanks

Retry queue

Learn retry queue and backoff.

Retry queue

If a network request fails, a common pattern is to write the request to a queue and retry later. This queue is called a retry queue. Each item carries a request object; when online, each item in the queue is tried in turn.

Failed items stay in the queue; they are retried on the next attempt. Successful ones are removed from the queue. This pattern gives resilience against temporary network errors. The queue can be made persistent with AsyncStorage; even if the app closes the queue is not lost. The queue's size is kept limited; very old items are dropped.

Queue processing

To process the queue you take each item in turn and try the network request. On success you remove the item from the queue; on failure the item stays in the queue. You do this with a while (queue.length > 0) loop.

Example: const item = queue[0]; try { await sendRequest(item); queue.shift(); } catch (e) { break; }. shift() removes the first item of the array. On error you break out of the loop; no other item is tried. This preserves the rest of the queue on error. When the queue is empty the synchronization is complete.

Practice Process the queue

Complete the processQueue function. Set up a while (queue.length > 0) loop. Inside the loop take const item = queue[0]; call await sendRequest(item); on success remove it with queue.shift(). On error break. queue and sendRequest are passed as parameters.

Starter code

App.js
export async function processQueue(queue, sendRequest) {
  // process the queue in turn
}

Sample solution

App.js
while (queue.length > 0) {
  const item = queue[0];
  try {
    await sendRequest(item);
    queue.shift();
  } catch (e) {
    break;
  }
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the queue add function

Question
queue.____(request);
Answer
queue.push(request);

Explanation: push adds the item to the queue.

2 How is a successful request removed from the queue?

App.js
await sendRequest(item); queue.???();
  • pop
  • shift Correct answer
  • remove
  • delete

Explanation: shift removes the first item.

3 Match each method to its purpose

Term Meaning
push Adds to queue
shift Removes first item
length Queue size
while Sets up loop

All lessons in Advanced