FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

One bad record, and Promise.all leaves client data in a blind spot

A rejection does not cancel the writes still in flight, so only per-record results from allSettled show what landed and whether a rerun is safe.

ShareLinkedInFacebookX

In brief

  • Promise.all rejects on the first error but does not cancel the remaining operations, so writes to the client's system keep going.
  • For independent records, Promise.allSettled gives the result of each record, so you can build a report and retry only the failures.
  • p-limit only caps how many tasks run at once. A quota measured in requests per second needs a separate mechanism such as a token bucket, plus retries on 429.
Decision tree. If tasks depend on each other (token, config, schema), use Promise.all. If not, use Promise.allSettled, highlighted in orange. Then consider the API limit: if it is measured in concurrent requests, use p-limit; if in requests per second, use p-limit together with a token bucket.
Promise.all suits dependent steps. Independent records in a sync run should use allSettled, paired with throttling that matches how the client's API counts its quota.

Five thousand contacts, one line of output: “sync failed”. Take an FDE at a client’s office running the first sync from a legacy system into a new CRM. A few seconds in, that line is all the terminal prints. The client asks how many records made it across and how many failed. There is no answer to give.

The fault usually lies somewhere other than the client’s API. It sits in a line of code that looks entirely harmless: await Promise.all(contacts.map(upsert)). Almost everyone new to asynchronous JavaScript has written it, and it works fine in a demo with 20 records.

For an FDE, this is a lesson in craft more than syntax. When integrating with a client, you have to be able to say which records went across, which failed and why, and whether a rerun is safe. Answering those three questions requires knowing exactly what each Promise function does.

Promise.all is designed to stop at the first error

According to MDN, Promise.all rejects as soon as any input promise rejects. This is fail-fast behavior. If one of the 5,000 contacts has a malformed email and the API returns 400, the whole await throws, and you lose the results for the other 4,999 records.

There is a more dangerous detail. MDN states plainly that rejecting the returned promise does not cancel the remaining operations. Your code has already jumped into catch and logged “sync failed”, while thousands of requests are still writing to the client’s CRM with nobody watching them.

The result is client data in a state no one fully understands. You assume the batch failed and run it again, when in fact most records were already written. If the write is not idempotent, the rerun creates duplicates, and the next meeting is spent cleaning up the client’s data instead of planning the next step.

Independent records need a different tool

MDN draws a clear line. Promise.allSettled is typically used when tasks do not depend on one another, or when you always want to know the outcome of each promise. Promise.all fits better when tasks depend on each other, or when you want to stop as soon as one fails.

Most data syncs fall into the first group: contact A failing has no bearing on contact B. Promise.all still has its place, for instance when you need both an auth token and configuration before starting, because without either one you cannot proceed.

Promise.all

  • Rejects on the first error
  • Remaining operations keep running, unmonitored
  • Suits dependent steps: token, config, schema
  • The batch must stop if one part is missing

Promise.allSettled

  • Waits for every task to finish
  • Returns status, value or reason for each task, in input order
  • Suits independent records in a sync
  • Lets you rerun only the failures

Per MDN, allSettled returns an array of results in the same order as the input. Each element has a status of “fulfilled” or “rejected”. A fulfilled result has a value field; a rejected one has a reason field. Because order is preserved, you can match each result back to its source record by index and get a per-record report straight away.

Switching to allSettled does not solve everything

Swap all for allSettled and nothing else, and you are still firing 5,000 requests at once. The client’s API will return a wave of 429 errors, and your report will show thousands of failed records simply because you sent them too fast.

The popular library for this is p-limit by Sindre Sorhus, which runs async functions with limited concurrency. You wrap each task in limit(...) and then collect results with Promise.all or allSettled as usual.

The p-limit README is explicit, though, that the library only caps how many tasks run at the same time. If the API quota is measured in requests per second, five parallel requests that each return very quickly can still exceed it.

Anvil’s article on 429 limits also points out that many SDKs, including those from major API providers, do not handle rate limiting themselves, so this part usually falls to you.

Rewriting the sync script

Here is a rewritten version using p-limit, retries on 429 and a per-record results report:

import pLimit from 'p-limit';

const limit = pLimit(5); // at most 5 requests in flight at once
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

function retryDelayMs(retryAfter, attempt) {
  if (retryAfter) {
    const value = String(retryAfter).trim();
    // Defensive: a value made only of digits is treated as seconds,
    // never passed to the date parser
    if (/^\d+$/.test(value)) return Number(value) * 1000;
    // HTTP-date format (not ISO 8601),
    // e.g. "Wed, 21 Oct 2026 07:28:00 GMT"
    const at = Date.parse(value);
    if (!Number.isNaN(at)) return Math.max(0, at - Date.now());
  }
  return 2 ** attempt * 1000; // header unreadable: fall back to backoff
}

async function upsertWithRetry(contact, attempt = 0) {
  try {
    return await crm.upsertContact(contact);
  } catch (err) {
    if (err.status === 429 && attempt < 5) {
      await sleep(retryDelayMs(err.headers?.['retry-after'], attempt));
      return upsertWithRetry(contact, attempt + 1);
    }
    throw err; // 400 or data error: no retry, record it in the report
  }
}

const settled = await Promise.allSettled(
  contacts.map((c) => limit(() => upsertWithRetry(c)))
);

const report = settled.map((r, i) => ({
  id: contacts[i].id,
  status: r.status,
  reason: r.status === 'rejected' ? String(r.reason?.message ?? r.reason) : null,
}));

const failedIds = report.filter((x) => x.status === 'rejected').map((x) => x.id);
console.log(`OK: ${report.length - failedIds.length}, failed: ${failedIds.length}`);

A few small details hold this script together. Because allSettled preserves order, contacts[i] always matches settled[i]. A 429 is retried and a data error is not, since resending a malformed email will fail however many times you try.

The retryDelayMs function is written defensively. According to Anvil, dates in Retry-After use the HTTP-date format rather than ISO 8601, so the function parses a date only after setting aside values that look like a plain number, and it always has a fallback backoff.

Do not blindly trust the date parser’s output on unusual input: a miscalculated delay can make the client hammer the API with retries at the very moment it is asking you to slow down.

Add a token bucket when the quota is per second

When the quota is measured in requests per second, Anvil considers a token bucket the best way to throttle on the client side. A “bucket” holds tokens that refill at a fixed rate, and each request must take a token before it is sent. Here is a minimal sketch:

// Token bucket sketch: at most `rate` requests per second
function createBucket(rate) {
  let tokens = rate;
  let last = Date.now();
  return async function take() {
    for (;;) {
      const now = Date.now();
      tokens = Math.min(rate, tokens + ((now - last) / 1000) * rate);
      last = now;
      if (tokens >= 1) { tokens -= 1; return; }
      await sleep(((1 - tokens) / rate) * 1000); // wait for a full token
    }
  };
}

const take = createBucket(10); // e.g. a quota of 10 requests per second

Call await take() immediately before crm.upsertContact(contact) inside upsertWithRetry, so that retries also have to queue for a token. p-limit still caps concurrency while the bucket caps the rate; the two layers work together, each covering what the other does not.

Anvil also argues that the ideal solution hides the limit entirely. Wrap take() and the retry logic in a dedicated client, so the sync code simply calls upsertContact without having to think about quotas.

Steps when you sit down with the client’s code

First, sort the work. Steps that depend on each other (authentication, reading the schema) stay on Promise.all. The per-record sync moves to allSettled. Next, ask the client or read the documentation to find out whether the quota counts concurrent requests or requests per second, then choose p-limit, a token bucket or both.

Then decide which errors deserve a retry. A 429 gets retried, with a cap on attempts and respect for Retry-After. Data errors go into the report. Finally, write the report to a file and prepare a command that reruns only failedIds, so the rerun never touches records that were written successfully.

Common mistakes

The first is wrapping Promise.all in try/catch and assuming that makes it safe. A catch cannot stop requests already in flight. The second is treating p-limit as a rate limiter, then being surprised by 429s. The third is retrying every error, including 400s, so that one broken record drags out the entire sync.

The last is mentioned least and does the most damage: logging only “sync failed” with no per-record report. The client does not care which Promise function you used. They care which 37 records did not make it across, and why.

Exercise: reproduce the bug before the client does

Write a fake API with Express or a mock function: one in every 100 records returns 400, and more than 5 concurrent requests returns 429 with a Retry-After header, sometimes a number and sometimes an HTTP-date.

Run the Promise.all version and count how many writes still happen after catch has run, then run the rewritten version above and compare the two reports.

The exercise also makes good material for your portfolio. In an FDE interview, describe how you found the bug, what you measured and how you fixed it.

On a CV, describe the concrete work, along the lines of “data sync with per-record reporting, throttling and 429 retries”, rather than a generic line such as “proficient in JavaScript”.

When a job description mentions integration, have this story ready to tell.

On a client site, trust comes from a sync where, when something does fail, you can say exactly which records failed and why. A sync that has never failed is rarely on offer.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
4 sources
Read next on the roadmap · Stage 1: FoundationsPython is in 66% of FDE postings, nearly double the next skillAcross 1,000 postings, TypeScript, agents, AWS and LLM experience cluster near one-third, which separates the baseline from the edge.