Polski

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.

medium · typescript · javascript · python · csharp · java · go · 20 XP

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

  1. CachingRateProvider(inner, ttl, now) – a caching proxy:

    • returns the cached rate while the entry is younger than its lifetime (now() - fetchedAt < ttl), then asks inner again;
    • 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.
  2. LazyRateProvider(factory) – a virtual (lazy) proxy: factory creates the real provider only on the first getRate, and only once. When the factory throws, the next call tries again.
  3. 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