AlgoViz

Adapter pattern

easy 50 min

The Adapter pattern makes an existing class fit the interface that its client expects, without changing either of them.

Watch lesson4:39

Failure and cost

Timeouts, retries, sync and async, logging, and what a layer really costs.

The point: an adapter around a network call owns four decisions that nobody else can make well: time limit, retry, translation of failure, and what is written to the log.

Who does what

Keep the adapter small

ConcernIn the adapter?Why
Time limit per callYesIt knows the vendor's normal times
Which failures may be repeatedYes, as error typesOnly it can read the vendor's codes
The retry loop itselfNo, a decorator around itThe same for all vendors: Decorator, retries
Circuit breakerNo, a wrapperCircuit breaker
Discounts, limits, fraud rulesNeverBusiness rules would have to be copied to each adapter
Mapping of fieldsYesThat is the job
Log of request and replyYes, without secretsIt sees the raw text. Card numbers and tokens are removed here
A useful test: if a second vendor would need the same code, it does not belong in the adapter.

Code

Adapter inside, retry outside

Python
class OutcomeUnknown(Exception):    passclass Declined(Exception):    passclass Retrying:    """Same interface as the gateway it wraps."""    def __init__(self, inner, attempts, wait):        self._inner, self._attempts, self._wait = inner, attempts, wait    def charge(self, money, key):        for attempt in range(1, self._attempts + 1):            try:                return self._inner.charge(money, key)            except OutcomeUnknown:                if attempt == self._attempts:                    raise                self._wait(0.2 * 2 ** (attempt - 1))    # 0.2, 0.4, ...class Flaky:    def __init__(self, failures):        self.failures, self.keys = failures, []    def charge(self, money, key):        self.keys.append(key)        if len(self.keys) <= self.failures:            raise OutcomeUnknown        return "receipt"waits = []gateway = Flaky(2)assert Retrying(gateway, 3, waits.append).charge(100, "order-9") == "receipt"assert gateway.keys == ["order-9"] * 3      # the same key every timeassert waits == [0.2, 0.4]class No:    calls = 0    def charge(self, money, key):        self.calls += 1        raise Declinedno = No()try:    Retrying(no, 3, waits.append).charge(100, "order-10")except Declined:    passassert no.calls == 1                        # a no is not repeatedprint("repeat silence, never a no")
This works only because the adapter kept the difference between silence and no. If both were one error, every refused card would be tried three times.
Edit and run it in your browser

Walk

Four failures, in order

What happensAdapterCaller
The vendor takes 30 sStops at 3 s, OutcomeUnknownRepeats with the same key, then shows "we are checking"
HTML instead of JSON (a proxy page)Parsing fails, OutcomeUnknown, raw text in the logThe same
A new field appearsIgnores itNotices nothing
A field that we need is missingOutcomeUnknown with the field's name, alarmThe same, and a person looks
Be generous with extra data and strict with missing data. Never fill a missing amount with 0.

Layers around one vendor

All four objects have the same interface. Only the innermost one knows the vendor.

Sync and async

Adapting the way of waiting

A blocking SDK inside an event loop stops everybody: while one call waits 300 ms, no other request moves. The adapter has to hand the call to a thread.

Python
import asyncioimport timeclass BlockingSdk:    def fetch(self, n):        time.sleep(0.05)        return n * nclass AsyncAdapter:    def __init__(self, sdk, limit):        self._sdk = sdk        self._places = asyncio.Semaphore(limit)     # not more threads than the vendor likes    async def fetch(self, n):        async with self._places:            return await asyncio.to_thread(self._sdk.fetch, n)async def main():    adapter = AsyncAdapter(BlockingSdk(), limit=4)    start = time.perf_counter()    answers = await asyncio.gather(*(adapter.fetch(n) for n in range(8)))    took = time.perf_counter() - start    assert answers == [n * n for n in range(8)]    assert took < 0.35          # two rounds of 0.05, not eight    print(answers, f"{took:.2f} s")asyncio.run(main())
8 calls of 50 ms with 4 places: about 100 ms instead of 400. The semaphore is part of the translation: the vendor's limit becomes ours. Cancelling the task does not stop the thread.
Edit and run it in your browser

What does the extra layer cost?

100 ns per call×1,000,000 calls/s=0.1 s of CPU per second100 \text{ ns per call} \times 1{,}000{,}000 \text{ calls/s} = 0.1 \text{ s of CPU per second}
Assumption: 100 ns for one extra Python method call; in Java or C++ it is often a few nanoseconds or is inlined. Around a network call of 50 ms, 100 ns is 0.0002 percent. Around each pixel of a picture it is too much: adapt the whole picture, not the pixel.

Good granularity

  • One adapter call per user action
  • Adapt a list as a list, one request
  • Map fields once, then work with your own type

Too fine

  • One vendor call per getter
  • for id in ids: adapter.get(id): 100 network calls
  • Lazy fields that call the vendor when printed