Skip to content

Working With Outside Services

Summary

Teaches how to call third-party APIs safely: adapters, validating responses, timeouts and retries, silent failures, and why every check needs a third result called not checked.

Concepts Covered

This chapter covers the following 26 concepts from the learning graph:

Concept Concept Impact Score
Third-Party Service 110
Data Sharing with Vendors 1
API Adapter 36
API Client Library 1
Vendor Response Validation 2
Schema Validation Library 1
Rate Limit 5
Timeout 16
Retry 15
Exponential Backoff 1
Idempotency 2
Silent Failure 28
Failure Read as Empty 5
Three-State Check Result 13
No False All-Clear Rule 5
Fail Closed or Fail Open 4
Graceful Degradation 3
Vendor Outage 14
Circuit Breaker 11
Vendor Lock-In 1
Webhook Verification 12
Payment Webhook 11
AI Model API 4
Model ID 3
Parallel Checks 4
Score Aggregation 3

Prerequisites

This chapter builds on concepts from:


A Quiet Smoke Alarm

Most homes have a smoke alarm on the hallway ceiling. On an ordinary night it does nothing at all. The family eats dinner, the kids go to bed, and the alarm stays quiet. That quiet tells everyone in the house that there is no smoke.

Now picture the same hallway a year later. The battery has run down to nothing. The alarm is still on the ceiling, and it is still quiet. From the kitchen table the house sounds exactly the same as it did the year before. But the quiet means something different now. It no longer says "no smoke." It says nothing at all, and nobody can tell the difference by listening.

Somebody else's ceiling

Sawyer waving welcome Most of what your app promises comes from companies you don't run. Each of them will have a bad day, and that part is certain. This chapter shows you how to make that bad day show up on the screen as a gap, so a member never reads it as good news.

The people who design smoke alarms know this, which is why a modern alarm chirps when its battery runs low. That small, annoying chirp gives the alarm a third thing to say. There is the loud alarm, which means smoke. There is silence, which means no smoke. And there is the chirp, which means "I can't tell you anything right now, so don't trust my silence." The chirp exists so that a broken alarm never sounds like a safe house.

Every outside service your app calls is a smoke alarm on somebody else's ceiling. This chapter is about giving each one a chirp.

Borrowing Someone Else's Work

A third-party service is software run by another company that your app calls over the internet to get something done. Your app sends a request to the other company's API, the way Chapter 2 described, and gets an answer back in JSON. You pay for the service, usually per call, and in return you get a skill your app couldn't easily build for itself. Stripe takes payments. An AI model reads text. An image-search company has already indexed billions of photos. A text-message company has the phone network connections.

AI agents make third-party services very easy to add. Ask for "a check that searches the web for this photo," and the agent will pick a vendor, read its documentation, and wire it in within an hour. That speed is a gift. It also means a typical app built with an agent leans on outside services far more than an app built the slow way. Each one is a part of your app that you don't run, can't see inside, and can't fix.

Almost every part of the dating-safety app's value comes from somebody else's servers.

Outside service What the app sends What it gets back Used for
Image-search vendor A member's uploaded photo of their match Web pages where the photo appears Spotting a photo stolen from someone else
AI model API Message text and voice-clip transcripts Patterns that match known scam scripts The message check
People-search vendor The match's phone number The name on the account and public records linked to it Checking that the person exists as described
Phone lookup vendor A phone number Carrier and line type Spotting throwaway numbers
SMS vendor A one-time code and a phone number A delivery status Sign-in codes and alerts
Stripe A checkout request A payment page, then a webhook Paying for scans

One Photo Check

Follow one check from start to finish. A member uploads a photo of the man she has been messaging. The app's server takes the photo from private storage and sends it to the image-search vendor. The vendor searches its index and, about three seconds later, answers with a list of web pages where that face appears. One of them is a stock-photo site, under a different name. The app turns that into a red flag on the results page.

Count the places in that short trip where something outside the app's control could go wrong. The vendor might be down. It might be slow. It might refuse the call because the app made too many calls this minute. It might answer with a JSON shape the app doesn't expect, because the vendor changed its API last Tuesday. The app's API key might have expired. Each of these happens to every vendor eventually. None of them is a bug in the app. What the app does next is entirely up to the app, and the rest of this chapter is about getting that part right.

Data Sharing with Vendors

Every call to a third-party service hands that company some of your users' data. Data sharing with vendors is the plain fact that whatever you send in a request now sits, at least for a while, on another company's servers under that company's rules. The image-search vendor receives a private photo. The people-search vendor receives a phone number. The AI model receives message text that may describe a painful situation.

Before the first call to a new vendor, read what it keeps and for how long, because a photo sent to a vendor that keeps it can't be unsent. Send the smallest piece of data that does the job: a cropped face instead of the whole photo, a phone number instead of the whole profile. Add each vendor to the data flow map from Chapter 8.

Tell your agent

"List every third-party service this app calls. For each one, write down what data we send it, what it sends back, what it costs per call, and where its terms say how long it keeps our data. Put this in a table in docs/vendors.md. Don't change any code."

Adapters: One Door per Vendor

When code talks to a vendor from many places, every one of those places has to know the vendor's quirks: its URL, its key, its JSON shape, its error codes. When the vendor changes, you have to find them all. The fix is to give each vendor one door.

An API adapter is a small piece of your own code that is the only place in the app that talks to one vendor. The rest of the app calls the adapter and gets back an answer in the app's own shape, not the vendor's. The adapter handles the URL, the key, the request format, the response format and the errors. If the vendor changes, you change one file.

Its most important job is the shape of what it returns. In the dating-safety app, every check adapter returns the same small object, whatever vendor sits behind it. Here is a sketch in TypeScript, the typed form of JavaScript from Chapter 3. The status field holds one of three words. The findings field holds what the check found, and reason explains a check that didn't run.

type CheckResult =
  | { status: "passed";  findings: [] }
  | { status: "failed";  findings: Finding[] }
  | { status: "not_checked"; reason: string };

Because every adapter returns this same shape, the scoring code never needs to know which vendor answered, or how. It only needs to know which of the three things happened.

An adapter also gives you one place to put the habits the next sections describe: a timeout, a retry rule, a check on the vendor's response. Put them in the adapter once and every caller gets them. Leave them out and each caller has to remember them, and some won't.

API Client Libraries

Many vendors publish an API client library, a package you install that wraps their API in ready-made functions. Stripe's package for Node.js is one. Instead of building the request by hand, your code calls something like stripe.checkout.sessions.create(...). Client libraries save time and often handle details such as signing requests.

A client library still belongs inside an adapter. The library speaks the vendor's language; the adapter turns that into yours. Read what the library does on failure, too. Some client libraries retry failed calls on their own, and if your adapter retries as well, one failure can turn into many calls.

Tell your agent

"Check whether each outside service in this app is called from exactly one adapter file, and whether every check adapter returns the same result shape with a status of passed, failed or not_checked. List any vendor called from more than one place and any adapter with a different shape. Then show me your plan to fix them before you change any code."

Checking What Comes Back

The dating-safety app read the vendors' JSON without checking it. The code asked for a field and used whatever was there. That works on the day the agent writes it, because the vendor answers the way its documentation says. It stops working the day the vendor answers differently, and nothing warns you.

Vendor response validation is checking that a vendor's answer has the shape and types your code expects before your code uses it. If the image-search vendor promises a list called matches, validation confirms that matches is there and is a list. If it isn't, the adapter treats the call as failed instead of guessing.

Here is how the gap shows up. Suppose the vendor renames matches to results in a new version of its API. Code that reads data.matches ?? [], which means "use matches, or an empty list if it's missing," doesn't crash. It gets an empty list. An empty list means "no matches found," and the photo check passes. Every scan from that day on says the photos are clean, and nothing in the app looks wrong.

Schema Validation Libraries

You don't have to write the checking code by hand. A schema validation library lets you describe the shape you expect once, and then checks any data against it. Zod is a common one for TypeScript. The sketch below describes what the image-search vendor should send back. The safeParse call checks the vendor's answer against that description and reports success or failure, instead of stopping the code with an error.

const VendorAnswer = z.object({
  matches: z.array(z.object({ url: z.string(), name: z.string() })),
});

const parsed = VendorAnswer.safeParse(body);
if (!parsed.success) {
  return { status: "not_checked", reason: "vendor sent an unexpected shape" };
}

When the vendor renames its field, safeParse fails, the check says "not checked," and the gap is visible on the results page. That is the chirp from the smoke alarm, written in code.

Tell your agent

"Plan how to add a Zod schema for each vendor's response in every adapter, and validate the response before using it. If validation fails, the adapter should return not_checked with a reason, never an empty result. Each adapter also needs a test that feeds it a response with a renamed field. Show me the plan, starting with one adapter, before you change the rest."

When the Call Goes Wrong

Outside services fail in a handful of ordinary ways, and an adapter that handles these few handles most of what a vendor can throw at it.

Timeouts

A timeout is a limit on how long your code will wait for an answer before it gives up. Without one, a call to a vendor that never answers can hold a scan open for minutes, and the member stares at a spinner. Chapter 1 walked through the slow people-search vendor and the choice to stop waiting after 10 seconds. That chapter made the decision. Here is where it lives: in the adapter, on every call.

Many of the code libraries that make web requests have no timeout by default, or a very long one. Ask your agent which tool your adapters use and what its default is. Then set a timeout on purpose for each vendor, based on how long it usually takes. A good starting point is about three times the vendor's normal answer time, so a vendor that usually answers in two seconds gets six to ten. A timeout is a failure like any other, and the adapter reports it as "not checked."

Rate Limits

A rate limit is a cap a vendor puts on how many calls you may make in a period of time, such as 10 calls per second or 1,000 per day. Go over it and the vendor refuses the call, usually with HTTP status 429, "Too Many Requests." Many vendors add a Retry-After header that says how many seconds to wait.

Rate limits bite apps that run checks in parallel. If twenty members start a scan in the same minute, the app may send far more calls to one vendor than it usually does. A 429 means "slow down," not "nothing found." Chapter 16 covers the other side of this idea, limiting how fast other people can call your API.

Retries and Exponential Backoff

A retry is trying a failed call again. Many failures are brief: a dropped connection, a vendor server restarting, a 429 that clears in a second. Trying once more often works. But retries have to follow rules, or they make things worse.

Retry only failures that might go away. A timeout, a 429 and a 5xx server error might. A 401 (bad key) or a 400 (bad request) won't, so retrying them just wastes time and money. Cap the number of tries. Three attempts in total is a common choice.

Wait between tries, and wait longer each time. Exponential backoff means doubling the wait after each failed try. If the first wait is 1 second, the waits run 1, 2, then 4 seconds. Written as a formula, the wait before retry number \( n \) is

\[ \text{wait}_n = \text{base} \times 2^{\,n-1} \]

where base is the first wait. Most adapters also add a small random amount, called jitter, so that a hundred scans that failed at the same moment don't all retry at the same moment too. Backoff gives a struggling vendor room to recover instead of hammering it.

Here is the retry plan for the image-search adapter, with a 10-second timeout and three attempts in total.

Attempt Wait before it What can end it If it fails
1 None Answer, error or 10-second timeout Retry if timeout, 429 or 5xx
2 1 second (or the Retry-After value) Same Retry if timeout, 429 or 5xx
3 2 seconds Same Stop. The check is "not checked."

Look at what the worst case costs. Three 10-second timeouts plus three seconds of waiting is 33 seconds for one check. That is the price of retrying, and it is why the timeout and the retry count have to be chosen together.

Idempotency

Retries raise a hard question: what if the first try worked and only the answer got lost? For a search, that costs nothing; the app searches twice. For a call that does something, such as sending a text message or charging a card, it means doing it twice.

An operation has idempotency when doing it twice has the same effect as doing it once. Reading data is idempotent. Sending a message is not. To make a call safe to retry, many vendors accept an idempotency key: a unique ID your app makes up and sends with the request. Stripe uses an Idempotency-Key header. If Stripe sees the same key twice, it returns the first result instead of charging again. For vendors without this, record what you have sent in your own database, and check before sending again.

Tell your agent

"For every adapter, show me its timeout, how many times it retries, which errors it retries, and how long it waits between tries. Then propose changes so that every outside call has a timeout, retries only timeouts, 429s and 5xx errors, makes at most three attempts in total, and uses exponential backoff and jitter. Never retry a call that sends a message or moves money unless it carries an idempotency key. Show me the proposed settings for each vendor before you change code."

Silent Failure

A timeout or a 429 is easy to handle once the adapter sees it. The harder failures are the ones the app never notices.

A silent failure is a failure that produces no error, no alert and no visible sign, so the app carries on as if nothing went wrong. The battery in the smoke alarm is a silent failure. Chapter 12 tells the author's own story of scheduled jobs that stopped with no error, and covers how to notice a job that never ran. This section is about a narrower and more common case in apps that call vendors.

Failure Read as Empty

Failure read as empty is a silent failure where code treats "the call failed" as "the call found nothing." It is a common way a vendor problem turns into a wrong answer, and it was one of the gaps found in the dating-safety app: a failed search call read as "no results."

It usually looks like this. The agent writes a search adapter, and to keep the app from crashing, it wraps the call in a try-catch block: code that tries the call and, if anything goes wrong, runs the catch part instead. Here the catch part returns an empty list. Chapter 12 calls this a bare catch block, because it catches every error and says nothing.

try {
  const res = await searchVendor(photo);
  return res.matches ?? [];
} catch {
  return [];   // a timeout, a 429, a bad key: all become "no matches"
}

Every kind of failure leaves the function looking like a successful search that found nothing. The results page then shows a green check next to "Photo search," and the member has no way to know that the search never happened. An agent often writes this when asked to make a feature robust, and it does keep the app from crashing. The fix is to report the failure in its own words:

} catch (err) {
  return { status: "not_checked", reason: describe(err) };
}

Read the catch block

Sawyer sharing a tip Here's a quick review habit. When an agent says it made a call "more robust" or "safer," open the catch block and read what it returns. An empty list, a zero or a true there is this bug.

The Question for Every Adapter

Ask one question of every adapter on the day it is written.

One question per adapter

Sawyer thinking If this silently fails, does the output still look fine? Ask it about your own code, not the vendor, because the vendor will fail sooner or later.

If the answer is yes, the adapter needs a third result and a test that proves it uses it. The diagram below traces seven ways one vendor call can end, and asks you to say what the member should see for each.

Diagram: Where a Vendor Failure Can Hide

Run the Where a Vendor Failure Can Hide MicroSim Fullscreen

Where a Vendor Failure Can Hide

Type: workflow sim-id: vendor-failure-paths
Library: Mermaid
Status: Specified
Bloom Level: Understand
Bloom Verb: classify
Learning Objective: The learner will classify each of seven ways an image-search call can end as passed, failed or not checked, and identify which of them a catch-all empty result turns into a false pass.

Prerequisites: third-party service, API adapter, timeout, rate limit, retry, vendor response validation, failure read as empty, the three results passed, failed and not checked (all defined in the sections above).

Evidence of Mastery: For each of the seven end points of the flow, the learner picks passed, failed or not checked before its infobox opens. A pick is correct when it matches the Correct result column. Mastery is 7 of 7. Reading the infoboxes after picking is exploration, not evidence.

Misconceptions: (1) A vendor error means the vendor found nothing. (2) A response with status 200 is always safe to use. (3) Retrying turns every failure into a success.

Instructional Rationale: Classifying end points one at a time makes the learner separate "the vendor said no" from "the vendor said nothing," which is the distinction a catch-all empty result erases. Showing the old code's answer beside the correct one makes the size of the gap visible.

Content:

The flow starts at "Adapter sends photo to image-search vendor" and branches as follows.

Step Question Yes leads to No leads to
1 Did the vendor answer within 10 seconds (after up to 3 attempts)? Step 2 End point E3
2 What HTTP status came back? 200: step 3; 429 after 3 attempts: E4; 5xx after 3 attempts: E5; 401: E7
3 Does the body pass the schema check? Step 4 End point E6
4 Does the list of matches hold a page with the face under another name? End point E1 End point E2
End point What happened Correct result What the old catch-all code showed Infobox text
E1 Valid answer with a match under another name Failed Failed The vendor found the photo elsewhere. This is a red flag the member needs to see.
E2 Valid answer with no matches Passed Passed The vendor searched and found nothing. This is a pass.
E3 No answer within 10 seconds on all 3 attempts Not checked Passed A timeout means the search never finished. It says nothing about the photo.
E4 429 Too Many Requests on all 3 attempts Not checked Passed The vendor refused the call because of its rate limit. No search happened.
E5 5xx server error on all 3 attempts Not checked Passed The vendor's server failed. No search happened.
E6 200, but the body is missing the matches field Not checked Passed The vendor changed its response shape. Reading a missing field as an empty list hides the change.
E7 401 Unauthorized Not checked Passed The API key was rejected, so no search happened. This one also needs an alert, because it won't fix itself. It is never retried.

Provenance: The failure-read-as-empty gap and unvalidated vendor JSON are from research/seed-notes.md. The 10-second timeout and three attempts are from the sections "Timeouts" and "Retries and Exponential Backoff" of this chapter. The seven end points are illustrative and must be labeled "illustrative."

Rules: An end point is Failed only when the vendor answered with a valid body that holds a red flag. It is Passed only when the vendor answered with a valid body and no red flag. Every other end point is Not checked. A 401 is not retried; the others are retried up to 3 attempts in total.

Learner Activity:

  1. The learner sees the whole flow with the seven end points hidden behind "?" labels.
  2. The learner clicks an end point and picks passed, failed or not checked.
  3. The end point reveals its correct result, the old code's result and its infobox text.
  4. After all seven, a summary shows how many of the seven end points the old code showed as Passed.
  5. The learner should notice that five of the seven end points look identical to a clean search under the old code.

Feedback: Seven end points, any order, one attempt each. Correct: "Right. " followed by the infobox text. Incorrect: "This one is [correct result]. " followed by the infobox text. The score "n of 7" is shown at the end, with "Mastery reached" at 7.

Starting State: The flow is shown with all end points hidden. The prompt reads "Seven ways one search can end. What should the member see for each?"

Chapter Anchors: The timeout is 10 seconds. There are 3 attempts in total. A 429 means "Too Many Requests." Of the seven end points, five (E3 to E7) showed as passed under the old catch-all code.

Tell your agent

"Search the code for every catch block, every ?? [] and every || [] near a call to an outside service. For each one, tell me whether a failure there could show up as an empty or clean result. Then show me a plan to change each adapter so a failure returns not_checked with a reason, with a test for each adapter that makes the vendor fail and checks the result. Wait for my go-ahead before changing code."

Three Answers, Not Two

The fix for silent failure is the smoke alarm's chirp: a third answer that means "I couldn't look."

A three-state check result is a check outcome that can be one of three values: passed (the check ran and found no problem), failed (the check ran and found a problem), or not checked (the check didn't run, or ran but couldn't be trusted). Most code is written with two states, true or false, found or not found. Two states have no room for "I don't know," so "I don't know" gets squeezed into one of the other two, and it nearly always lands on the comfortable one.

Our adapter shape from earlier already carries three states. The rest of the app has to carry them too. The database column that stores a check's result needs three values, not a true-or-false flag. The results page needs a third look: a gray "Not checked" label with the reason and a button to run the check again. And the score needs a rule for what not-checked counts as.

The No False All-Clear Rule

The no false all-clear rule says that a check that didn't run must never be counted as passed, and if no check ran at all, the score is a neutral 50, never a reassuring high number. Chapter 1 explained why this is a must-be-right part: a member who reads "all clear" when nothing was checked might meet a scammer in person.

The rule is easy to state and easy to break by accident. Here are three ways code breaks it without anyone meaning to.

Code How it breaks the rule
catch { return []; } A failed search becomes "no matches," which is a pass.
const score = passedCount / checksRun * 100 One passing check and seven failures to run gives 100.
if (results.length === 0) return 100; No results at all becomes a perfect score.

A rule this important needs a test that runs on every change. Chapter 1 named that test: turn off every vendor, run a scan, and expect a 50 with eight "not checked" labels. Chapter 10 shows how to make that kind of test part of every build.

Fail Closed or Fail Open

When a check can't run, the app has to choose which way to lean. Fail closed or fail open is that choice. A part that fails closed refuses or blocks when it isn't sure: a door with an electric lock that stays locked when the power goes out. A part that fails open allows or carries on when it isn't sure: a fire exit that unlocks when the power goes out.

Neither is always right. The question is which mistake costs less.

Part of the app When it can't decide Choice Why
Trust score Treat unknown as not safe, never as clear Fail closed A false all-clear can hurt a member
Webhook signature check Reject the request Fail closed Accepting a fake payment event gives away scans
Daily scan cap lookup Stop new scans until the cap can be read Fail closed Running past the cap can run up a large bill
Spam filter on the contact form Let the message through Fail open A spam message costs little; a lost member question costs more
Analytics tracking Skip it and carry on Fail open Nobody is harmed by a missing page view

Graceful Degradation

Failing closed doesn't mean failing completely. Graceful degradation means the app keeps doing what it still can when one part breaks, and says plainly what it couldn't do. If the image-search vendor is down, the other seven checks still run. The member gets a score built from what ran, with the photo check marked "Not checked: the image search service didn't respond. Try again in a few minutes." That report is less complete, and it is still useful and still truthful.

Tell your agent

"Trace a check result from the adapter to the database to the results page to the score. At each step, show me whether 'not checked' survives as its own value or gets turned into passed or failed. Write the all-vendors-down test: expect a score of 50 and every check labeled not checked. Then show me your plan for any step that loses 'not checked' before you fix it."

Running Checks Side by Side

The dating-safety app runs about eight checks for each scan. Run one after another, each taking a few seconds, a scan would take most of a minute. Parallel checks means starting all the checks at the same time and waiting for all of them to finish. The scan then takes about as long as the slowest check, not the sum of all of them.

Parallel checks bring one trap of their own. In JavaScript, the usual way to wait for several calls at once is Promise.all. If any one of the calls throws an error, Promise.all gives up on the whole group at once. One vendor outage then sinks all eight checks. The safer tool is Promise.allSettled, which waits for every call and reports each one's outcome separately. Better still, if every adapter catches its own failures and returns not checked, no single check can bring the others down.

Two other habits keep parallel checks safe. Give each check its own timeout, so one slow vendor can't hold the whole scan open. And keep an eye on rate limits, because twenty members scanning in the same minute send twenty calls to every vendor at once, 160 calls in all.

Score Aggregation

Once the checks finish, the app has to turn eight results into one number. Score aggregation is the rule that combines several check results into a single score. It is where three-state results either survive or get lost.

Here is one simple rule that keeps them. It is an illustration, not the dating-safety app's exact formula. Each passed check counts as 100, each failed check counts as 0, and each not-checked check counts as a neutral 50. The score is the average over all eight checks:

\[ \text{score} = \frac{100 \times \text{passed} + 0 \times \text{failed} + 50 \times \text{not checked}}{8} \]

If nothing ran, the score is 50. If one check passed and seven didn't run, the score is \( (100 + 7 \times 50) / 8 = 56.25 \), which rounds to 56. That number stays close to neutral, which is what the member should hear when the app knows very little.

Compare a common rule an agent might write: average only the checks that ran. One passing check and seven not run gives 100. The app knows almost nothing, and it says "all clear." Showing a coverage line next to the score, such as "3 of 8 checks ran," helps too, because a member can see at a glance how much the number rests on.

What 50 means

Sawyer thinking Notice that a neutral 50 is not a guess that the match is half likely to be a scammer. It says the app knows little. Read it next to the coverage line, never on its own.

Diagram: Score Aggregation Explorer

Run the Score Aggregation Explorer MicroSim Fullscreen

Score Aggregation Explorer

Type: microsim sim-id: score-aggregation-explorer
Library: p5.js
Status: Specified
Bloom Level: Analyze
Bloom Verb: compare
Learning Objective: The learner will compare the scores that two aggregation rules give for the same eight check results, and identify the scenarios where the rule that averages only the checks that ran produces a false all-clear.

Prerequisites: three-state check result, no false all-clear rule, parallel checks, score aggregation (all defined in the sections above).

Evidence of Mastery: For each of five fixed scenarios, the learner marks whether Rule B's score is a false all-clear, before the scores are revealed. A mark is correct when it matches the Rules definition. Mastery is 5 of 5. Changing check states freely in the sandbox is exploration, not evidence.

Misconceptions: (1) Dropping checks that didn't run makes the score more accurate. (2) A score of 100 means every check ran and passed. (3) A neutral 50 means the match is half likely to be a scammer.

Instructional Rationale: Comparing two rules on the same inputs isolates the one difference that matters, what not-checked counts as. Committing a judgment before seeing the numbers makes the learner reason from the rule rather than react to the score.

Content:

The eight checks, each shown as a tile that can be set to passed, failed or not checked (illustrative):

  1. Photo search
  2. Face match
  3. AI-generated photo check
  4. Message pattern check
  5. Voice clip check
  6. People-search records
  7. Phone line type
  8. Known-scam phrase list

Rule A (neutral 50): passed counts 100, failed counts 0, not checked counts 50; the score is the average over all 8 checks.

Rule B (drop the unknowns): the score is the average over checks that ran, with passed as 100 and failed as 0; if no check ran, the score is 100.

The five scenarios:

Scenario Check states Rule A score Rule B score False all-clear under Rule B? Why (feedback)
1 All 8 passed 100 100 No Every check ran, so 100 is supported.
2 All 8 not checked 50 100 Yes Nothing ran, yet Rule B says all clear.
3 Check 4 passed, the other 7 not checked 56 100 Yes One check ran. Rule B speaks as if all eight did.
4 Checks 1 to 6 passed, check 7 failed, check 8 not checked 81 86 No Seven of eight ran. Both scores are supported, and both are below 90.
5 Checks 4 to 6 passed, checks 1, 2, 3, 7 and 8 not checked 69 100 Yes The image vendor and two others were down. Rule B hides five gaps.

Provenance: The neutral score of 50 when nothing ran and the roughly eight checks are from research/seed-notes.md. The check names, the two rules and the five scenarios are illustrative and must be labeled "illustrative; not the dating-safety app's exact formula."

Rules: Scores round to the nearest whole number, with .5 rounding up. A Rule B score is a false all-clear when it is >= 90 and three or more of the eight checks are not checked. The coverage line reads "n of 8 checks ran," where n counts passed and failed checks.

Learner Activity:

  1. The learner sees scenario 1: eight tiles with their states, and both score dials hidden.
  2. The learner marks "False all-clear" or "Supported" for Rule B, then presses Reveal.
  3. Both scores and the coverage line appear, with the Why text.
  4. The learner moves through scenarios 2 to 5 in order.
  5. After scenario 5, a sandbox opens where the learner can click any tile to cycle it through passed, failed and not checked and watch both scores and the coverage line change.
  6. The learner should notice that Rule B jumps to 100 whenever the checks that ran all passed, however few they were.

Feedback: Five scenarios, fixed order, one attempt each. Correct: "Right. " followed by the Why text. Incorrect: "Look again. " followed by the Why text. The running count "n of 5" is shown, with "Mastery reached" at 5.

Starting State: Scenario 1 with eight passed tiles. The prompt reads "Two rules, same results. Which score can a member trust?"

Chapter Anchors: About eight checks run per scan. Rule A scores 50 when nothing ran. One passed check with seven not checked scores 56 under Rule A (56.25 before rounding) and 100 under Rule B. The coverage line reads "n of 8 checks ran."

Tell your agent

"Show me the code that runs the checks for a scan and the code that turns their results into a score. Tell me whether the checks run in parallel with Promise.allSettled or with adapters that never throw, and whether each has its own timeout. Write tests for the score: all not checked gives 50, and one passed with seven not checked never gives more than 60. Then propose any fixes, plus a line on the results page that says how many of the checks ran, and show me the plan before changing code."

When a Vendor Goes Down

A vendor outage is a stretch of time when a third-party service doesn't work for anyone, from a few minutes to a few hours. Every vendor has them. Large ones publish a status page that lists them. For an app built on eight vendors, the odds that at least one is having a bad hour on any given day are higher than most builders expect.

Three-state results and graceful degradation already make an outage safe for members. They don't make it cheap or fast. Each scan during the outage still waits out every timeout and every retry, about 33 seconds with the plan from earlier, and pays for any calls the vendor bills even when they fail. Two hundred scans during an hour-long outage is two hundred members waiting half a minute for an answer the app could have known in advance.

Circuit Breakers

A circuit breaker is a guard in the adapter that stops calling a vendor for a while after it has failed several times in a row. Its name comes from the switch in a house's electrical panel, which trips and cuts the power when something goes wrong, so the wiring doesn't overheat. Michael Nygard made the pattern widely known in his 2007 book Release It!. Chapter 13 uses the same idea for spending, a breaker that stops calls when a bill climbs too fast. This one trips on failures.

A circuit breaker has three states.

  • Closed. Calls go through as normal. The breaker counts failures in a row. A success resets the count.
  • Open. After, say, 5 failures in a row, the breaker opens. For the next 30 seconds every call is skipped at once, and the check returns "not checked: service unavailable" without waiting.
  • Half-open. When the 30 seconds are up, the breaker lets one trial call through. If it works, the breaker closes. If it fails, the breaker opens again for another 30 seconds.

With a breaker in place, the first few scans of an outage wait out their timeouts, and every scan after that gets an instant, truthful "not checked." When the vendor recovers, the first trial call notices, and normal service resumes on its own. The breaker's state changes are also exactly the events worth an alert, which Chapter 12 covers.

Diagram: Circuit Breaker Step-Through

Run the Circuit Breaker Step-Through MicroSim Fullscreen

Circuit Breaker Step-Through

Type: microsim sim-id: circuit-breaker-step-through
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: use
Learning Objective: The learner will use the three-state circuit breaker rules to predict the breaker's state and each scan's photo-check result across a sequence of calls during a vendor outage and recovery.

Prerequisites: vendor outage, circuit breaker and its closed, open and half-open states, not checked (all defined in the sections above).

Evidence of Mastery: At each of the six checkpoints in the fixed sequence, the learner predicts the breaker state (closed, open or half-open) and, at checkpoints where a call arrives, the result that call gives (passed, not checked after waiting, or not checked at once). A prediction is correct when every part matches the answer table. Mastery is 5 of 6 checkpoints correct.

Misconceptions: (1) A breaker stays open until someone resets it by hand. (2) An open breaker means the check is marked passed. (3) One failed call opens the breaker.

Instructional Rationale: Predicting the next state from the rules, then seeing it happen, is application of a procedure. The fixed sequence covers every transition once, including a failed trial call, so the learner uses each rule at least once.

Content:

Rules shown on screen: Failure threshold 5 failures in a row. Open period 30 seconds. Half-open allows 1 trial call.

The fixed sequence (the vendor is down from 0:00 to 1:10 and healthy after that; times are minutes:seconds; synthetic):

Time Event Breaker state after Photo-check result
0:00 Call 1 times out Closed (1 failure) Not checked after waiting
0:05 Calls 2 to 4 time out Closed (4 failures) Not checked after waiting
0:10 Call 5 times out Open Not checked after waiting
0:15 Call 6 arrives (checkpoint 1) Open Not checked at once
0:40 Open period ends (checkpoint 2) Half-open none
0:41 Trial call 7 fails (checkpoint 3) Open Not checked after waiting
0:50 Call 8 arrives (checkpoint 4) Open Not checked at once
1:11 Open period ends, vendor healthy (checkpoint 5) Half-open none
1:12 Trial call 9 succeeds (checkpoint 6) Closed (0 failures) Passed

Provenance: The three states, the 5-failure threshold and the 30-second open period are from the section "Circuit Breakers" of this chapter. The timeline is synthetic and must be labeled "synthetic example."

Rules: In Closed, each failure adds 1 to the count and each success resets it to 0; when the count reaches >= 5, the state becomes Open. In Open, every call is skipped and returns not checked at once, until 30 seconds have passed since the breaker opened. Then the state becomes Half-open. In Half-open, the next call goes through: success sets Closed with count 0; failure sets Open and restarts the 30 seconds.

Learner Activity:

  1. The learner presses Step to move to the next event.
  2. At each checkpoint, the sim pauses and asks for the breaker state and the next result.
  3. After the learner answers, the sim shows the state and result, and the scan counter updates.
  4. A running tally shows how many calls waited out a timeout and how many were answered at once.
  5. The learner should notice that only 6 of the 9 calls waited, and that the breaker closed again with no one touching it.

Feedback: Six checkpoints, fixed order, one attempt each. Correct: "Right. " plus the rule that applied. Incorrect: "Not quite. The breaker is [state] because " plus the rule that applied. The correct answer is shown after each attempt. Score "n of 6," with "Mastery reached" at 5 or more.

Starting State: The breaker shows Closed with a failure count of 0 and the vendor shows Down. The prompt reads "The vendor just went down. What will the breaker do?"

Chapter Anchors: The breaker opens after 5 failures in a row. The open period is 30 seconds. Half-open lets 1 trial call through. The three states are closed, open and half-open.

Vendor Lock-In

Outages raise a bigger question. What if a vendor doesn't come back, or doubles its price, or changes its terms in a way you can't accept? Vendor lock-in is how hard it would be to move from one vendor to another. It grows every time vendor-specific code spreads through the app. A clean adapter keeps it small: switching image-search vendors means writing one new adapter that returns the same result shape, and nothing else changes. Chapter 1's set-based design applies here too. Writing a second adapter for a rival vendor before you need it is cheap with an agent, and it turns a crisis into a configuration change.

Tell your agent

"Plan a circuit breaker for every check adapter: open after 5 failures in a row, stay open 30 seconds, then allow one trial call. While the breaker is open, return not_checked with the reason 'service unavailable' without calling the vendor. Log every time a breaker opens or closes. Show me the plan for one adapter before you build it. Also tell me which vendor would be hardest to replace and why."

Calls That Come to You: Webhooks

So far the app has been the one calling out. Some vendors call in. Chapter 2 introduced the webhook, a request a vendor sends to your app's endpoint when something happens on its side. Stripe sends one when a payment succeeds. An SMS vendor sends one when a message is delivered. Webhooks bring two problems that outgoing calls don't have: you don't know who is calling, and the same news can arrive more than once.

Webhook Verification

A webhook endpoint is a public address on the internet. Anyone who finds it can send it a request that looks exactly like a vendor's. Webhook verification is checking that a webhook came from the vendor before acting on it.

Most vendors sign each webhook. They take the body of the request and a secret that only you and they know, run them through a signing function, and put the result in a header. Stripe's is called Stripe-Signature. Your endpoint repeats the same calculation with its copy of the secret and compares. If the results match, the request came from Stripe and wasn't changed on the way. If they don't, you reject it. The webhook secret is a secret like any other, and Chapter 6 covers how to store and rotate it.

Three details trip up agent-written webhook code:

  1. Verify the raw body. The signature covers the exact bytes the vendor sent. If the server reads the JSON into an object first and turns it back into text, the bytes change and the check fails. Agents often "fix" that failure by removing the check.
  2. Check the timestamp. Stripe's signature includes the time it was sent, and its libraries reject anything older than five minutes by default. That stops someone from recording a valid webhook and sending it again later.
  3. Fail closed. A webhook that fails verification gets an error response and does nothing else. No "log it and carry on."

Watch the diff

Sawyer warning A common trap: the signature check fails during testing, and the agent makes the error go away by deleting or skipping the check. Before you accept a change to a webhook endpoint, look for any line that removes or bypasses verification. If you find one, ask the agent to read the raw body instead.

Payment Webhooks

A payment webhook is a webhook a payment provider sends to tell your app that money has moved: a checkout completed, a payment failed, a refund went through. It is how the dating-safety app learns that a member has paid for scans. In Stripe's case, the app sends the member to a Stripe checkout page, and when the payment goes through, Stripe sends a checkout.session.completed event to the app's webhook endpoint. The app checks that the session's payment status is "paid" and then adds scan credits to the member's account.

This is the money path, and the dating-safety app's payment webhook was untested, one of the gaps found later. Here is what can go wrong with it, worked through.

Stripe delivers each event at least once, which means sometimes more than once. If your endpoint doesn't answer quickly with a success status, Stripe retries the event, with backoff, for up to three days. Now picture the endpoint adding five credits and then timing out before it replies. Stripe tries again. The endpoint adds five more. The member paid for five scans and got ten. Turn it around, with an endpoint that crashes before it adds the credits but after it replies, and the member paid and got nothing.

Here the idempotency idea from earlier does the work. Each Stripe event has a unique ID. The endpoint records the IDs it has handled in the database, in the same transaction as the credits. A transaction is a group of database changes that are all saved or none are; Chapter 11 covers it. When an event arrives, the endpoint checks the ID first. Already handled? Reply with success and do nothing. New? Add the credits and record the ID together, then reply. Events can also arrive out of order, so the endpoint should read the payment's current state rather than trust the order the events came in.

Step Without these habits With them
Request arrives Trusted as from Stripe Signature and timestamp checked on the raw body
Duplicate event Credits added twice Event ID already recorded, so nothing happens
Crash halfway Paid, no credits, or credits, no record Credits and event ID saved together, or neither
Fake event from a stranger Free scans Rejected with an error

Chapter 10 makes this the first path to test, alongside sign-in.

Tell your agent

"Show me our Stripe webhook endpoint. Confirm it verifies the Stripe-Signature header against the raw request body, rejects anything that fails, and records each event ID in the same database transaction as the credits it grants, so a repeated event does nothing. Write tests that send a valid event twice, an event with a bad signature, and an event older than five minutes. If any test fails, show me your plan before changing the endpoint, because this is the money path."

AI Models Are Outside Services Too

It is easy to think of the AI model as part of the app. It isn't. An AI model API is a third-party service that takes a prompt and returns text or structured data from a large language model, the kind Chapter 4 described. Every rule in this chapter applies to it. It has rate limits. It has outages. It can be slow, so it needs a timeout. Its answers need validation, because a model asked for JSON sometimes sends plain sentences, or JSON with a missing field, or a polite refusal. And it costs money per call, which Chapter 13 covers.

AI model APIs add one failure that other vendors rarely have. A model ID is the exact name of the model your code asks for in each call. Model providers release new models often and retire old ones on a published schedule. When a model is retired, calls that ask for it by its old ID start returning errors.

Here is how that plays out. The message check names its model ID in the adapter. Months later, the provider retires that model. If the adapter swallows errors, the message check now passes every scan, because a failed call reads as "no scam patterns found." No one notices for weeks. If the adapter returns not checked, every scan shows the gap the same day, the coverage line drops from 8 of 8 to 7 of 8, and the fix is a one-line change. Keep model IDs in one configuration file, not scattered through the code, so that one-line change is one line. Chapter 13 makes the same point about model prices.

Two safety habits also live in the AI adapter. Text from web pages and from the match's messages goes to the model fenced off as untrusted data, marked so the model reads it as material and never as instructions. Chapter 16 explains how. And a model may suggest who a person is, but the code never names anyone unless a source page confirms it, which is Chapter 8's verify-before-naming rule.

Tell your agent

"Find every AI model ID in this codebase and tell me where each one appears. Tell me the retirement date for each model we use, if the provider has announced one. Then plan the changes: move every model ID into one config file, and in every AI adapter add a timeout, validate the model's JSON answer with a schema, and return not_checked if the call fails, the answer doesn't fit the schema, or the model refuses. Show me the plan before changing code."

The Adapter Checklist

Every habit in this chapter fits in one adapter, and together they answer the question from the silent failure section: if this silently fails, does the output still look fine? Here they are together, in the order you'd add them.

Habit What it prevents Where it lives
One adapter per vendor Vendor quirks spread through the app One file per vendor
Three-state result A failure reads as a pass The adapter's return type
Response validation A changed API reads as "nothing found" A schema check on every answer
Timeout A scan hangs on a slow vendor Every outgoing call
Retry with backoff A brief failure becomes a gap Timeouts, 429s and 5xx only
Idempotency A retry sends a message or charges twice Any call that does something
Circuit breaker Every scan waits out a long outage The adapter, per vendor
Webhook verification Fake events give things away Every webhook endpoint
Model IDs in one place A retired model breaks a check quietly One config file
A failing-vendor test Any of the above coming undone The test suite

You don't need all of these on day one for every vendor. Chapter 1's question still applies: what happens if this one is wrong? For the checks that feed the trust score and for the payment webhook, the answer is that someone gets hurt or money goes missing, so they get the full list. For an analytics call, a timeout and fail-open is plenty.

Tell your agent

"For each adapter in this app, go through this checklist and add the results to docs/vendors.md: one adapter, three-state result, response validation, timeout, retries with backoff, idempotency where needed, circuit breaker, model ID in config. Mark each item done or missing in a table. Then answer for each adapter: if it silently fails, does the output still look fine? For the ones where the answer is yes, propose fixes in order of harm and wait for my go-ahead."

Back to the Smoke Alarm

The chirp on a smoke alarm costs a few cents of circuitry, and it is the only reason a family can trust the alarm's silence. Without it, a quiet hallway could mean a safe house or a dead battery. The dating-safety app makes eight of those promises on every scan. Each check's silence says "I looked and found nothing," and that only holds if the check can also say "I couldn't look." Chapter 10 covers the tests that keep that third answer working on every change.

A chirp for every check

Sawyer celebrating You can now look at any outside call and say what the member sees when it fails: passed, failed or not checked. You also know the timeouts, retries, circuit breakers and webhook checks that keep that third answer in place. Good enough for now, and you know why.

Key Takeaways

  • Put each vendor behind one API adapter that returns the same three-state result: passed, failed or not checked.
  • Validate every vendor response, set a timeout on every call, and retry only failures that might clear. Use idempotency keys on any call that sends a message or moves money.
  • Failure read as empty turns a failed search into a clean one. A check that didn't run never counts as passed, and a scan where nothing ran scores 50.
  • A circuit breaker turns a long vendor outage into fast, truthful "not checked" answers.
  • Verify every webhook's signature on the raw body, and make a payment webhook safe to receive twice.
  • For every adapter, ask: if this silently fails, does the output still look fine?

See Annotated References