Adapter pattern
easy 50 minThe 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
| Concern | In the adapter? | Why |
|---|---|---|
| Time limit per call | Yes | It knows the vendor's normal times |
| Which failures may be repeated | Yes, as error types | Only it can read the vendor's codes |
| The retry loop itself | No, a decorator around it | The same for all vendors: Decorator, retries |
| Circuit breaker | No, a wrapper | Circuit breaker |
| Discounts, limits, fraud rules | Never | Business rules would have to be copied to each adapter |
| Mapping of fields | Yes | That is the job |
| Log of request and reply | Yes, without secrets | It sees the raw text. Card numbers and tokens are removed here |
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")Walk
Four failures, in order
| What happens | Adapter | Caller |
|---|---|---|
| The vendor takes 30 s | Stops at 3 s, OutcomeUnknown | Repeats with the same key, then shows "we are checking" |
| HTML instead of JSON (a proxy page) | Parsing fails, OutcomeUnknown, raw text in the log | The same |
| A new field appears | Ignores it | Notices nothing |
| A field that we need is missing | OutcomeUnknown with the field's name, alarm | The same, and a person looks |
Layers around one 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())What does the extra layer cost?
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