Exchange-rate caching proxy
Two proxies in front of a slow bank API – a caching one with an entry lifetime and a lazy one that connects only on first use. They share one interface, so they compose.
The shop converts prices to euros and dollars, asking the bank for the rate every time a cart is displayed. The bank API takes 800 ms, has a rate limit, and setting up the connection itself (certificates, login) takes a few seconds. The shop code only knows the RateProvider interface with getRate(currency) – and that should stay so. The answer is the Proxy pattern: objects with the same interface that stand in front of the real provider and control access to it.
Task
CachingRateProvider(inner, ttl, now)– a caching proxy:- returns the cached rate while the entry is younger than its lifetime (
now() - fetchedAt < ttl), then asksinneragain; - every currency has its own entry and the lifetime counts from the latest fetch;
- provider errors reach the caller and are not cached – the next call asks the bank again.
- returns the cached rate while the entry is younger than its lifetime (
LazyRateProvider(factory)– a virtual (lazy) proxy:factorycreates the real provider only on the firstgetRate, and only once. When the factory throws, the next call tries again.- Both proxies implement
RateProvider, so they can be nested:CachingRateProvider(LazyRateProvider(factory), …).
The clock is injected so the tests can move time: a function returning milliseconds (TypeScript, JavaScript, Python, Java – a LongSupplier), a Func<DateTime> with a TimeSpan ttl (C#) and a func() time.Time with a time.Duration (Go). In Go the method is Rate(currency) (float64, error), in Python get_rate, in C# GetRate.
Topics: Proxy
Related articles
- Proxy – a stand-in that controls access to the real object
Proxy has the same interface as the real object and stands in front of it, deciding when – and whether – to pass a call on. An invoice archive example with access control and a lazy connection in C#, TypeScript, Java, Go and Python.