SOLID in one page
medium 45 minFive principles for classes that can be changed without fear: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Watch lesson5:16
In production
Retry, fallback and limits without opening the service: the five letters under load.
The point: real senders are slow, fail and repeat. Because of the contract, each protection can be a wrapper that is a sender itself. The service never learns about it.
Design
Wrappers that keep the promise
A sender around a sender
1/4Unchanged
The service and its port. Nothing here will be edited on this page.
usesimplements
Protective wrappers
Two wrappers with the same shape.
from dataclasses import dataclass@dataclass(frozen=True)class Receipt: ok: bool detail: str = "" retry: bool = False # may it work if we try again?class Retrying: def __init__(self, inner, tries, pause): self.name, self._inner, self._tries, self._pause = inner.name, inner, tries, pause def send(self, to, text): for n in range(1, self._tries + 1): r = self._inner.send(to, text) if r.ok or not r.retry or n == self._tries: return r self._pause(2 ** (n - 1))class Fallback: def __init__(self, name, senders): self.name, self._senders = name, list(senders) def send(self, to, text): why = [] for s in self._senders: r = s.send(to, text) if r.ok: return Receipt(True, "by " + s.name) why.append(s.name + ": " + r.detail) return Receipt(False, "; ".join(why))Lines 4 to 8
The contract grew by one optional field. Old senders say nothing and mean: do not retry. That is a change which asks no more of anybody.
Failure walk
| Event | Plain service | With wrappers |
|---|---|---|
| Gateway busy for 2 seconds | Failed | Retry, about 3 seconds later it works |
| Gateway down all night | Failed, history only | Fallback: email |
| 500 equal alerts in one minute | 500 messages | 1 message |
| Mail server hangs | The loop waits for ever | Still waits. A wrapper cannot stop a call from outside: the adapter needs a timeout |
| Process dies after sending | Sent, not in the history | Same. An outbox is needed |