Skip to content

Module 06 · Lesson 6.4

Integrating an External Service

40 minUpdated 19 Nov 2026Part of Authentication and Integrations · New Project Creation
On this page
  1. What you will learn
  2. Why an outside service needs care
  3. A narrow adapter with a timeout
  4. The outbox: never lose a message
  5. Stubs, sandboxes and synthetic data
  6. Step-by-step workflow
  7. Working with an assistant on integrations
  8. Conclusion and your next step
  9. Reusable prompt
  10. Expected output
  11. Common errors and fixes
  12. Validation checklist
  13. Hands-on exercise
  14. Knowledge check
  15. Frequently asked questions
  16. References

When you post a parcel, you hand it to the clerk and leave. You do not stand at the counter until it arrives. You keep a receipt, and if something goes wrong, you can check. Talking to an outside service from your application works best the same way.

In this lesson, Tidewell connects to one outside service: a service that sends email. You wrap it in a small adapter, give every call a time limit, retry only when it is safe, and keep every message in an outbox table so nothing is lost. You test it all without ever calling a real provider.

What you will learn

  • Explain why an outside service is a risk to contain, and name four ways it can fail.
  • Wrap a service in a narrow adapter with a timeout, safe error answers and no leaked secrets.
  • Retry only when it is safe, using an idempotency key, and give up after a limit.
  • Use an outbox table so a failed call never loses a message, and test it with a stub, a fake fetch and synthetic data.

Before you start

  • Completed Roles and Permissions, or have a backend with sessions and a permission check.
  • Access to any capable AI assistant.
  • Optional: Node.js and the project from earlier lessons, if you want to run the examples.

Why an outside service needs care

Tidewell needs to send email: booking confirmations, waiting-list offers, and the sign-in links from the last lesson. Writing an email server is a poor use of one developer's time.

So Tidewell uses an outside email-sending service. That is an integration.

Integration
Your application calling, or being called by, someone else's system.
Adapter
A small piece of your code that is the only door to the outside service. The rest of the code talks to the adapter, never to the service.
Timeout
The longest you will wait for an answer. After that, you stop waiting. It is like hanging up when nobody answers the phone.
Retry
Trying a failed call again. It is only safe when doing it twice has the same effect as doing it once.
Idempotency key
A unique label you attach to a request. If the service sees the same label twice, it treats the second request as a repeat and does not send again. Not every service supports this, so read the docs.
Outbox
A table in your own database where messages wait to be sent. Your data is saved first, and the sending happens afterwards.
What can go wrongExampleOur answer
The service is slow or downThe email provider takes 30 seconds to reply, and the patient waits on a blank screen.A timeout, and sending from an outbox, never inside the booking request.
A message is sent twiceA retry sends a second confirmation.An idempotency key on every message.
Secrets or personal data leakThe API key or the message text ends up in a log.The key stays on the server. Logs hold ids and outcomes only.
The service changesA field is renamed, or a rule is tightened.One adapter to update, with tests around it.

A narrow adapter with a timeout

The adapter is a promise in code form: "send this message, and tell me what happened". The rest of Tidewell never sees addresses, headers or status codes from the provider. It sees only this.

TypeScriptsrc/lib/email.ts (the contract)
// src/lib/email.ts: the narrow door to the email provider. Nothing else in Tidewell talks to it.
export interface EmailMessage {
  to: string;
  subject: string;
  text: string;
  idempotencyKey: string;
}

export type SendResult = { ok: true; providerId: string } | { ok: false; retryable: boolean; reason: string };

export interface EmailSender {
  send(message: EmailMessage): Promise<SendResult>;
}

// A fictional provider. Real providers differ in address, headers and rules: read their docs.
const PROVIDER_URL = "https://email-provider.example/v1/messages";
  • EmailMessage holds exactly what a message needs: who, what, and the idempotency key.
  • SendResult is one of two shapes. Success returns the provider's own id. Failure says whether a retry could help, and gives a short reason. The result is data, so callers handle it with an ordinary if.
  • EmailSender is the whole interface: one method. A stub or a different provider can replace the real one without touching the rest of the code.

Here is the real adapter. It uses fetch and an AbortSignal.timeout, so a call that takes longer than the limit is cancelled. fetch is passed in so tests can supply a fake, the same trick as in the lesson Calling the API from the Frontend.

TypeScriptsrc/lib/email.ts (the real adapter)
export function createHttpEmailSender(options: { apiKey: string; fetchFn?: typeof fetch; timeoutMs?: number }): EmailSender {
  const fetchFn = options.fetchFn ?? fetch;
  const timeoutMs = options.timeoutMs ?? 5000;
  return {
    async send(message) {
      try {
        const response = await fetchFn(PROVIDER_URL, {
          method: "POST",
          headers: {
            Authorization: `Bearer ${options.apiKey}`,
            "Content-Type": "application/json",
            "Idempotency-Key": message.idempotencyKey,
          },
          body: JSON.stringify({ to: message.to, subject: message.subject, text: message.text }),
          signal: AbortSignal.timeout(timeoutMs),
        });
        if (response.ok) {
          const data = (await response.json().catch(() => null)) as { id?: unknown } | null;
          return { ok: true, providerId: typeof data?.id === "string" ? data.id : "unknown" };
        }
        // Reasons name only the status number: never the key, the address or the message text.
        const retryable = response.status === 408 || response.status === 429 || response.status >= 500;
        return { ok: false, retryable, reason: `provider answered ${response.status}` };
      } catch (error) {
        const timedOut = error instanceof Error && error.name === "TimeoutError";
        return { ok: false, retryable: true, reason: timedOut ? `no answer within ${timeoutMs} ms` : "network error" };
      }
    },
  };
}

What each part does

  • The key goes only in the Authorization header, on the server. It is never printed, returned or put in a reason.
  • Idempotency-Key carries the message's own key. If a call times out and is repeated, the provider can recognise the repeat.
  • AbortSignal.timeout(timeoutMs) limits the wait. The default is 5000 milliseconds. The test shortens it to 50 so it finishes quickly.
  • A good answer returns ok with the provider's id. A bad answer returns retryable and a plain reason such as provider answered 500. The reason holds only a status number, never the body, the address or the key.
  • A timeout or a network error is retryable. The adapter cannot know whether the provider received the request, so the idempotency key is what makes a retry safe.
OutcomeRetry?Why
SuccessNoThe message was accepted.
Timeout or network errorYesNothing is known. The key stops a repeat from sending twice, if the provider supports it.
408, 429 or 5xxYesThe provider was busy or broken, and may recover.
Another 4xx, such as 400NoThe request itself is wrong. Sending it again gets the same answer, so a person must look.

Test the adapter with a fake fetch

The test never goes near a real provider. It gives the adapter a fake fetch that behaves as the test says: succeeds, hangs, fails with 500, refuses with 400, or loses the network. The data is made up.

TypeScripttest-email.ts (the fake fetch and the scenarios)
// A fake fetch: records the call, then behaves as the test says.
function fakeFetch(behave: (init: RequestInit) => Promise<Response>): typeof fetch {
  return (async (input: RequestInfo | URL, init?: RequestInit) => {
    calls.push({ url: String(input), init: init ?? {} });
    return behave(init ?? {});
  }) as typeof fetch;
}

// A provider that never answers. The ticking timer only keeps this test process alive until the timeout fires.
const hangsUntilAborted = (init: RequestInit) =>
  new Promise<Response>((_, reject) => {
    const keepAlive = setTimeout(() => {}, 10_000);
    init.signal?.addEventListener("abort", () => {
      clearTimeout(keepAlive);
      reject(init.signal?.reason);
    });
  });

const scenarios: [string, (init: RequestInit) => Promise<Response>][] = [
  ["success", async () => Response.json({ id: "msg-123" }, { status: 201 })],
  ["slow provider", hangsUntilAborted],
  ["provider error 500", async () => new Response("oops", { status: 500 })],
  ["bad request 400", async () => Response.json({ error: "invalid address patient.a@example.com" }, { status: 400 })],
  ["network failure", async () => { throw new TypeError("fetch failed"); }],
];

const reasons: string[] = [];
for (const [label, behave] of scenarios) {
  const sender = createHttpEmailSender({ apiKey: API_KEY, fetchFn: fakeFetch(behave), timeoutMs: 50 });
  const result = await sender.send(message);
  if (!result.ok) reasons.push(result.reason);
  console.log(`${label}: ${JSON.stringify(result)}`);
}
Five answers from the adapter, and what it sentCaptured from a real run
success: {"ok":true,"providerId":"msg-123"}
slow provider: {"ok":false,"retryable":true,"reason":"no answer within 50 ms"}
provider error 500: {"ok":false,"retryable":true,"reason":"provider answered 500"}
bad request 400: {"ok":false,"retryable":false,"reason":"provider answered 400"}
network failure: {"ok":false,"retryable":true,"reason":"network error"}
request: POST https://email-provider.example/v1/messages
Authorization is a bearer token: true
Idempotency-Key: booking-confirmation-1
body fields: to, subject, text
any failure reason contains the key, address or text: false

Each of the five outcomes gives the answer the table above promised. The last lines check three more things. The request went to the right address, with a bearer key and the idempotency key.

The body has only three fields. And no failure reason contains the key, the address or the text.

The outbox: never lose a message

Suppose the booking is saved and then the email call fails. The patient has a booking and no confirmation. Suppose instead the email is sent first and the booking then fails.

The patient has a confirmation for nothing. Either order can go wrong.

The fix is an outbox. Tidewell writes the message into its own table, in the same statement that saves the booking. Both succeed or neither does.

A separate job sends the waiting messages later. The blog post The Transactional Outbox Pattern: Reliable Event Publishing with AI covers the general idea.

SQLdb/migrations/005_email_outbox.sql
-- Messages waiting to be sent. Written in the same statement as the change that caused them.
CREATE TABLE email_outbox (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  to_address text NOT NULL,
  subject text NOT NULL,
  body text NOT NULL,
  idempotency_key text NOT NULL UNIQUE,
  status text NOT NULL CHECK (status IN ('pending', 'sent', 'failed')),
  attempts int NOT NULL DEFAULT 0,
  last_error text,
  created_at timestamptz NOT NULL DEFAULT now(),
  sent_at timestamptz
);
  • idempotency_key is unique. A booking can write only one confirmation, because the key contains the booking's id.
  • status is pending, sent or failed. Only a person looks at failed rows.
  • attempts and last_error record what happened. The error text holds only the safe reason from the adapter.
  • The table holds an address and a message, which are personal data. Agree with the clinic owner how long sent rows are kept (CON-01).

Now the booking statement from Module 4 gets one more part. It adds a third piece to the single `WITH ...

RETURNING` query: the confirmation row. The booking, its history row and its confirmation are saved together or not at all.

TypeScriptsrc/features/bookings/service.ts (createBooking, with the confirmation)
export async function createBooking(ctx: BookingContext, slotId: number): Promise<BookingView> {
  const sql = `
    WITH new_booking AS (
      INSERT INTO bookings (slot_id, patient_id, status, created_at)
      SELECT s.id, $2, 'booked', $3 FROM slots s WHERE s.id = $1 AND s.starts_at > $3
      RETURNING id, slot_id, status
    ), change AS (
      INSERT INTO booking_changes (booking_id, action, actor_role, actor_id, to_slot_id, changed_at)
      SELECT id, 'created', 'patient', $2, slot_id, $3 FROM new_booking
    ), confirmation AS (
      INSERT INTO email_outbox (to_address, subject, body, idempotency_key, status)
      SELECT p.email, 'Your Tidewell appointment is booked',
             'Your appointment is booked for ' || to_char(s.starts_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI') || ' UTC.',
             'booking-confirmation-' || nb.id, 'pending'
      FROM new_booking nb JOIN slots s ON s.id = nb.slot_id JOIN patients p ON p.id = $2
    )
    SELECT ${VIEW_COLUMNS}
    FROM new_booking b JOIN slots s ON s.id = b.slot_id JOIN clinicians c ON c.id = s.clinician_id`;
  try {
    const { rows } = await ctx.db.query<BookingRow>(sql, [slotId, ctx.patientId, ctx.now.toISOString()]);
    if (rows.length === 0) throw notFound(); // no such slot, or it has already started
    return toView(rows[0]);
  } catch (error) {
    if (isOneLiveBookingViolation(error)) throw slotTaken();
    throw error;
  }
}
A booking writes its own confirmationCaptured from a real run
1. A booking writes its confirmation in the same statement
   booking: 201
   outbox: [{"id":1,"status":"pending","attempts":0,"last_error":null,"idempotency_key":"booking-confirmation-1"}]
   a second patient tries the same slot: 409 | outbox rows: 1

The booking returned 201, and one pending row appeared. Then a second patient tried the same slot.

That request got 409, and the number of outbox rows stayed at one. A refused booking leaves no message behind.

The sender job

A small job reads the pending rows and gives each to the adapter. Run it on a schedule, such as once a minute. How you schedule it depends on your hosting, so decide it and write it in your operating notes.

TypeScriptsrc/lib/outbox.ts (sendPending)
export async function sendPending(db: Db, sender: EmailSender, now: Date, log: (line: string) => void) {
  const { rows } = await db.query<OutboxRow>(
    `SELECT id::int AS id, to_address, subject, body, idempotency_key, attempts
     FROM email_outbox WHERE status = 'pending' ORDER BY id LIMIT 20`,
  );
  const tally = { sent: 0, failed: 0, waiting: 0 };
  for (const row of rows) {
    const result = await sender.send({
      to: row.to_address,
      subject: row.subject,
      text: row.body,
      idempotencyKey: row.idempotency_key,
    });
    const attempts = row.attempts + 1;
    if (result.ok) {
      await db.query("UPDATE email_outbox SET status = 'sent', attempts = $2, sent_at = $3 WHERE id = $1", [
        row.id,
        attempts,
        now.toISOString(),
      ]);
      tally.sent++;
    } else {
      const giveUp = !result.retryable || attempts >= MAX_ATTEMPTS;
      await db.query("UPDATE email_outbox SET status = $2, attempts = $3, last_error = $4 WHERE id = $1", [
        row.id,
        giveUp ? "failed" : "pending",
        attempts,
        result.reason,
      ]);
      if (giveUp) tally.failed++;
      else tally.waiting++;
    }
    // Log ids and outcomes only: never the address, the subject or the text.
    log(JSON.stringify({ level: "info", event: "email_attempt", outboxId: row.id, ok: result.ok, attempts }));
  }
  return tally;
}
  • The job takes at most 20 rows at a time, oldest first.
  • A success marks the row sent. A failure that could recover keeps it pending and counts the attempt.
  • After MAX_ATTEMPTS tries (a constant set to 5 in the same file), or at once for a refusal that retrying cannot fix, the row becomes failed. A person looks at it.
  • The log line holds an outbox id and an outcome. It never holds the address, the subject or the text.
  • If the job crashes after the provider accepted a message but before the row was marked sent, the next run sends it again. The same idempotency key lets the provider treat it as a repeat.

A real job would also wait longer between attempts. Keep it simple at first, and add that only when you need it.

Run one copy of the job at a time. If you ever run several, read about row locking in PostgreSQL first.

Watch the outbox handle trouble

A happy send, then a provider that keeps failingCaptured from a real run
2. The job sends it
   run 1: {"sent":1,"failed":0,"waiting":0} | messages given to the provider: 1
   message: {"to":"patient.a@example.com","subject":"Your Tidewell appointment is booked","text":"Your appointment is booked for 2026-12-01 10:00 UTC.","idempotencyKey":"booking-confirmation-1"}
   run 2 (nothing waiting): {"sent":0,"failed":0,"waiting":0}
3. A provider that keeps failing: five attempts, then failed
   run 1: {"sent":0,"failed":0,"waiting":1} | row 2 is pending after 1 attempt(s)
   run 2: {"sent":0,"failed":0,"waiting":1} | row 2 is pending after 2 attempt(s)
   run 3: {"sent":0,"failed":0,"waiting":1} | row 2 is pending after 3 attempt(s)
   run 4: {"sent":0,"failed":0,"waiting":1} | row 2 is pending after 4 attempt(s)
   run 5: {"sent":0,"failed":1,"waiting":0} | row 2 is failed after 5 attempt(s)
   run 6: {"sent":0,"failed":0,"waiting":0} (a failed row is left for a person to check)

In run 1 the stub accepts the message, and the row is sent. In the second block, the provider fails five times.

The row stays pending for four runs and fails on the fifth. In run 6 nothing happens: a failed row is left for a person.

Recovery, an unfixable refusal, and the final tableCaptured from a real run
4. Two failures, then success: nothing lost
   run 1: {"sent":0,"failed":0,"waiting":1}
   run 2: {"sent":0,"failed":0,"waiting":1}
   run 3: {"sent":1,"failed":0,"waiting":0}
5. A refusal that retrying cannot fix: failed at once
   run 1: {"sent":0,"failed":1,"waiting":0}
final outbox:
   {"id":1,"status":"sent","attempts":1,"last_error":null,"idempotency_key":"booking-confirmation-1"}
   {"id":2,"status":"failed","attempts":5,"last_error":"provider answered 500","idempotency_key":"booking-confirmation-3"}
   {"id":3,"status":"sent","attempts":3,"last_error":"no answer within 5000 ms","idempotency_key":"booking-confirmation-4"}
   {"id":4,"status":"failed","attempts":1,"last_error":"provider answered 400","idempotency_key":"booking-confirmation-5"}
log lines: 10 | any log line contains an address: false

In block 4 two failures were followed by a success, so the row ended up sent after three attempts. Block 5 shows a 400: the row failed after one attempt, because trying again cannot help. The last line proves the logs held no address.

Look at the keys in the final table. The second row has booking-confirmation-3, not 2.

The failed booking attempt in step 1 used up booking number 2. Gaps like this are normal.

Stubs, sandboxes and synthetic data

Tests should never send real email. They run all the time, often by machines, and a mistake would reach a real inbox. Use a stand-in that records what it was asked to send.

TypeScriptsrc/lib/email.ts (the stub)
// For tests: records every message it is given, and answers from a script (default: success).
export function createStubEmailSender(script: SendResult[] = []) {
  const received: EmailMessage[] = [];
  const sender: EmailSender = {
    async send(message) {
      received.push(message);
      return script.shift() ?? { ok: true, providerId: `stub-${received.length}` };
    },
  };
  return { sender, received };
}
  • The stub keeps every message it is given in an array called received, so a test can check what would have been sent.
  • It answers from a script. By default it succeeds. A test can give it a list of failures, as the outbox tests do.
  • It implements the same EmailSender interface, so the job cannot tell the difference.
WhereWhat sendsReal emails?
Unit and integration testsThe stub, or the real adapter with a fake fetch.Never.
Staging, a copy for checkingThe real adapter in the provider's sandbox or test mode, if it has one.No. Use only addresses you own.
ProductionThe real adapter with the real key.Yes.

Rules that keep an integration safe

  • Synthetic data only. Test addresses end in example.com. Never copy real patients into a test, a sandbox or an assistant.
  • The key stays on the server. In Next.js, only variables whose names start with NEXT_PUBLIC_ are sent to the browser. EMAIL_API_KEY must never get that prefix. The lesson Configuration and Secrets shows how it is read once at start-up.
  • Log outcomes, not content. Ids, counts and reasons are fine. Keys, addresses and message bodies are not. The Logging Cheat Sheet (opens in a new tab) lists what to leave out.
  • Sign-in links go straight out. A sign-in link is useless after a few minutes, so it should not wait in a queue. Many libraries let you supply a function that sends the sign-in email. Use the adapter there, if your library allows it, and show an honest "try again" message when it fails.

Step-by-step workflow

  1. Step 1: Write down what you need from the service

    List the messages, who triggers them and what must happen when they fail. Keep to what a requirement asks for.

    What you should see: A short list of messages and failure rules.

  2. Step 2: Read the provider's documentation

    Find the request format, the limits, the error codes, whether it supports idempotency keys and whether it has a sandbox. Do not rely on a summary, even your assistant's.

    What you should see: Notes with links to the pages you used.

  3. Step 3: Write the adapter interface first

    Define the one method and its two kinds of answer. Then write the real adapter behind it, with a timeout.

    What you should see: An interface that hides every provider detail.

  4. Step 4: Add the outbox

    Write the migration. Add the message row to the same statement as the change that causes it.

    What you should see: A refused change leaves no message. An accepted one leaves exactly one.

  5. Step 5: Write the sender job

    Send pending rows, count attempts, give up after a limit and log only outcomes.

    What you should see: A failed row waits for a person, and no log line holds personal data.

  6. Step 6: Test with a stub and a fake fetch

    Cover success, timeout, a server error, a refusal, a network error and recovery. Use synthetic data only.

    What you should see: Every failure path has a test, and none reaches a real provider.

  7. Step 7: Check once in the sandbox

    On a staging copy, send to addresses you own using the provider's test mode. Then switch the key for production through configuration, not code.

    What you should see: One real round trip, with no real patients involved.

How a message travels
  1. Booking saved

    With its history row

  2. Outbox row

    Same statement

  3. Sender job

    Every minute

  4. Adapter

    Timeout, key

  5. Provider

    Sandbox or real

  6. Row updated

    Sent or failed

The first two boxes happen in one statement. The rest happen later, in the job.

Working with an assistant on integrations

TaskAssistant's partYour part
List failure modesProposes timeouts, duplicates, rate limits and bad input from your description.Decide which matter and what the system must do for each.
Draft the adapterWrites the interface and a first version.Check it against the provider's own docs. Fields and headers it suggests may be invented.
Write the testsDrafts a fake fetch and the scenarios.Make sure each can fail, and that none can reach a real provider.
Handle secretsNothing. Do not paste real keys.Keep the key in .env.local and the hosting settings only.
Choose a providerSummarises features.Compare real docs, data location (CON-01) and cost, and record the choice in an ADR.

Conclusion and your next step

An outside service is a risk to contain. Tidewell puts one narrow adapter in front of it, with a timeout, safe retries and clean error answers. Messages wait in an outbox that is written in the same statement as the change. Tests use a stub and a fake fetch with made-up data.

Your next step: list the outside services your capstone will use, and write the adapter interface for one of them, with its failure answers. Then continue to Approvals for Consequential Actions, where some of those messages wait for a person to approve them.

For more on keys and secrets, read Managing API Keys Locally, or see how a similar clinic is built in Appointment Booking Portal.

Reusable prompt

Integration failure-mode review

Asks the assistant to list how an outside integration can fail and what the system should do for each, without writing code or inventing provider details.

You are reviewing the design of an integration. Do not write code. Do not invent features, fields or limits of any provider. If you are unsure of a provider detail, write "Check the provider's documentation".

Fictional clinic: Tidewell Physiotherapy. Stack: TypeScript, Next.js, PostgreSQL. One outside service: an email-sending service for booking confirmations and waiting-list offers.

Design so far:
- A narrow server-side adapter with one method, send(message), that returns success or a failure marked retryable or not.
- Each call has a 5-second timeout. Each message has an idempotency key.
- Messages are written to an outbox table in the same SQL statement as the booking change. A job sends pending rows, tries up to 5 times, then marks the row failed for a person to check.
- Tests use a stub sender and a fake fetch with synthetic data. The API key is read on the server only.

Tasks:
1. List failure modes that this design does not yet handle, each with the effect on patients and on the data.
2. For each, say what the system should do, in one sentence.
3. List what must never appear in logs, and what may.
4. List the tests you would add, one line each.
5. List every decision that needs a person under "Decision needed", with the role who should decide.
Show the reusable template

Replace each {{placeholder}} with your own details.

You are reviewing the design of an integration. Do not write code. Do not invent features, fields or limits of any provider. If you are unsure of a provider detail, write "Check the provider's documentation".

Context: {{organisation_stack_and_outside_service}}

Design so far:
{{adapter_timeout_retry_outbox_and_test_design}}

Tasks:
1. List failure modes that this design does not yet handle, each with the effect on users and on the data.
2. For each, say what the system should do, in one sentence.
3. List what must never appear in logs, and what may.
4. List the tests you would add, one line each.
5. List every decision that needs a person under "Decision needed", with the role who should decide.

Expected output and limitations

A list of failure modes with the effect and the intended behaviour of each, a short logging rule, a list of extra tests, and a Decision needed list with roles. A good answer says "Check the provider's documentation" instead of inventing details.

Sample responseIllustrative — your output will differ
1. Gaps
   - A message is accepted by the provider, then the job crashes before the row is marked sent.
     Effect: the patient may get two emails. Behaviour: resend with the same idempotency key.
   - The job runs twice at once. Effect: two sends. Behaviour: run one copy, or lock the rows.
   - Sent rows are never deleted. Effect: personal data kept without a reason.

3. Logs
   Never: the API key, the address, the subject or the text. May: outbox id, outcome, attempt count.

5. Decision needed
   How long are sent rows kept? Role: clinic owner (CON-01).
   Who checks failed rows, and how often? Role: practice manager.

Check the provider's documentation
   Whether it supports idempotency keys, and for how long.

Limitations to keep in mind

  • The assistant does not know your provider's real behaviour. Treat every claim about it as unverified until you find it in the docs.
  • It may suggest queues, brokers or services you do not need. Prefer the simplest design that fits your size.
  • A list of failure modes is not a test. Only a run with a fake fetch shows what the adapter really does.

Common errors and how to fix them

The email is sent inside the booking request.

Why it happens: It was the shortest code, and it worked in testing.

Fix: Write the message to the outbox in the same statement, and send it from a separate job.

Every failure is retried, including a 400.

Why it happens: "Retry on error" was applied without asking whether a retry could ever help.

Fix: Mark each failure retryable or not. Retry only the ones that might recover, and use an idempotency key.

A log line holds the API key, an address or the message text.

Why it happens: The whole request or response was logged "to help debugging".

Fix: Log ids, outcomes and counts only, and test that the logs hold no address.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

A low-stock alert for Ferngate

Ferngate Cycle Repairs wants an email to the owner when a part runs low. Design the adapter interface, list the failure cases and the answer to each, write the columns for an outbox table, and say what you will and will not log.

You will need

  • Note: the low-stock threshold is still "to be agreed" with the owner.
  • Note: the workshop's internet is unreliable, and mechanics use a shared tablet.
  • The Tidewell adapter and outbox from this lesson, as a pattern to adapt.

Acceptance criteria

Your work is done when every one of these is true.

Hints (2)
  • The workshop's connection matters when a mechanic saves a part. Does it also matter when the server sends the alert?
  • Think about an alert that is sent twice every time the count goes up and down around the threshold. Is that a decision for the owner?
Show a model answer

A strong answer copies the shape of the Tidewell adapter: one send method that returns success, or a failure marked retryable. It lists timeout, network error, 500, 429, 400 and a duplicate alert, and retries all but the 400. The outbox has an idempotency key built from the part and the day, a status, attempts and a last error. Logs hold the outbox id and the outcome. The key, the owner's address and the message text are never logged. The unreliable workshop connection affects recording a part on the tablet, not sending an alert from the server, which is a useful distinction. The threshold, and how often an alert may repeat, are decisions for the owner. An invented number would turn a guess into a rule.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why does Tidewell write the confirmation email to an outbox instead of sending it inside the booking request?
    Show the answer and explanation

    Answer: B. The outbox row is saved in the same statement as the booking, so one cannot exist without the other. A job sends it later and can retry. Slowness is tempting as the reason, but the real problem is failure and lost messages. Next.js routes can call outside services without trouble.

  2. 2.The provider answers 400 for a message. What should the job do?
    Show the answer and explanation

    Answer: B. A 400 means the request itself is wrong, so sending it again gets the same answer. Retrying is tempting because "retry" is the usual habit, but it only delays the problem. Deleting the row would lose the evidence that a patient never got a message.

  3. 3.What is an idempotency key for?
    Show the answer and explanation

    Answer: B. The same key on a repeated request tells the provider it is a repeat, which makes a retry safe, if the provider supports keys. It is not encryption and not a login. The API key does the job of proving who is calling, which is why the third option is tempting but wrong.

Frequently asked questions

What is an adapter in programming?

An adapter is a small piece of code that stands between your application and something outside it. The rest of your code talks to the adapter in your own simple terms. Only the adapter knows the outside system's details, so a change there means changing one file.

Why do API calls need a timeout?

Without one, a slow service can make your own page wait without end. A timeout says how long you will wait before giving up. Then your code can decide what to do, such as retry later.

When is it safe to retry a failed request?

It is safe when doing it twice has the same effect as doing it once. An idempotency key can give you that for requests that send or create something, if the service supports it. Do not retry errors that mean your request is wrong, such as a 400.

How do I test an integration without calling the real service?

Pass in a stand-in. For the adapter, give it a fake fetch that returns the answers you want to test. For the code around it, use a stub that records what it was asked to send. Use made-up data every time.

Written by
PromptFable Editorial
Last updated 19 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.