{"id":"6b093dc291bd8fbaf2a0c8e0","slug":"rate-caching-proxy","title":"Exchange-rate caching proxy","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["proxy"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["proxy","caching","lazy-loading","ttl","structural"],"languages":[{"lang":"typescript","runner":"browser","starter":"/** The subject: the real implementation calls the bank's slow API. */\ninterface RateProvider {\n  getRate(currency: string): number;\n}\n\n/**\n * Caching proxy: returns a cached rate while it is younger than `ttlMs` (now() - fetchedAt < ttlMs),\n * otherwise asks `inner` again. Every currency has its own entry. Failures are not cached.\n */\nclass CachingRateProvider implements RateProvider {\n  constructor(\n    private readonly inner: RateProvider,\n    private readonly ttlMs: number,\n    private readonly now: () => number = () => Date.now(),\n  ) {}\n\n  getRate(currency: string): number {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\n/**\n * Virtual (lazy) proxy: creates the real provider with `factory` on the first getRate() call, only once.\n * When the factory throws, the next call tries again.\n */\nclass LazyRateProvider implements RateProvider {\n  constructor(private readonly factory: () => RateProvider) {}\n\n  getRate(currency: string): number {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"function fakeBank(rates) {\n  const bank = {\n    calls: [],\n    getRate(currency) {\n      bank.calls.push(currency);\n      if (!(currency in rates)) throw new Error('Unknown currency: ' + currency);\n      return rates[currency];\n    },\n  };\n  return bank;\n}\n\nfunction fakeClock() {\n  const clock = { t: 0, now: () => clock.t };\n  return clock;\n}\n\ntest('the caching proxy returns the real rate and asks the bank once', () => {\n  const bank = fakeBank({ EUR: 4.3 });\n  const rates = new CachingRateProvider(bank, 60000, fakeClock().now);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(bank.calls).toEqual(['EUR']);\n});\n\ntest('every currency is cached separately', () => {\n  const bank = fakeBank({ EUR: 4.3, USD: 3.9 });\n  const rates = new CachingRateProvider(bank, 60000, fakeClock().now);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('USD')).toBe(3.9);\n  rates.getRate('EUR');\n  rates.getRate('USD');\n  expect(bank.calls).toEqual(['EUR', 'USD']);\n});\n\ntest('an entry expires after the TTL', () => {\n  const table = { EUR: 4.3 };\n  const bank = fakeBank(table);\n  const clock = fakeClock();\n  const rates = new CachingRateProvider(bank, 60000, clock.now);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  table.EUR = 4.35;\n  clock.t = 59999;\n  expect(rates.getRate('EUR')).toBe(4.3);\n  clock.t = 60000;\n  expect(rates.getRate('EUR')).toBe(4.35);\n  expect(bank.calls).toHaveLength(2);\n});\n\ntest('the TTL counts from the latest fetch', () => {\n  const bank = fakeBank({ EUR: 4.3 });\n  const clock = fakeClock();\n  const rates = new CachingRateProvider(bank, 60000, clock.now);\n  rates.getRate('EUR');\n  clock.t = 60000;\n  rates.getRate('EUR');\n  clock.t = 100000;\n  rates.getRate('EUR');\n  expect(bank.calls).toHaveLength(2);\n  clock.t = 120000;\n  rates.getRate('EUR');\n  expect(bank.calls).toHaveLength(3);\n});\n\ntest('failures are not cached', () => {\n  const flaky = {\n    attempts: 0,\n    getRate() {\n      this.attempts++;\n      if (this.attempts === 1) throw new Error('Bank API timeout');\n      return 4.3;\n    },\n  };\n  const rates = new CachingRateProvider(flaky, 60000, fakeClock().now);\n  expect(() => rates.getRate('EUR')).toThrow('Bank API timeout');\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(flaky.attempts).toBe(2);\n});\n\ntest('the lazy proxy creates the real provider on first use, only once', () => {\n  let created = 0;\n  const lazy = new LazyRateProvider(() => {\n    created++;\n    return fakeBank({ EUR: 4.3 });\n  });\n  expect(created).toBe(0);\n  expect(lazy.getRate('EUR')).toBe(4.3);\n  expect(lazy.getRate('EUR')).toBe(4.3);\n  expect(created).toBe(1);\n});\n\ntest('a failed creation is retried on the next call', () => {\n  let created = 0;\n  const lazy = new LazyRateProvider(() => {\n    created++;\n    if (created === 1) throw new Error('Connection refused');\n    return fakeBank({ EUR: 4.3 });\n  });\n  expect(() => lazy.getRate('EUR')).toThrow('Connection refused');\n  expect(lazy.getRate('EUR')).toBe(4.3);\n  expect(created).toBe(2);\n});\n\ntest('proxies share the interface of the real provider, so they stack', () => {\n  const quote = (provider, currency, amount) => Math.round(amount * provider.getRate(currency) * 100) / 100;\n  let bank = null;\n  const stacked = new CachingRateProvider(\n    new LazyRateProvider(() => (bank = fakeBank({ EUR: 4.3 }))),\n    60000,\n    fakeClock().now,\n  );\n  expect(bank).toBeNull();\n  expect(quote(stacked, 'EUR', 100)).toBe(430);\n  expect(quote(stacked, 'EUR', 10)).toBe(43);\n  expect(bank.calls).toEqual(['EUR']);\n});\n"},{"lang":"javascript","runner":"browser","starter":"// The subject (RateProvider) is any object with getRate(currency) → number.\n// The real implementation calls the bank's slow API.\n\n/**\n * Caching proxy: returns a cached rate while it is younger than `ttlMs` (now() - fetchedAt < ttlMs),\n * otherwise asks `inner` again. Every currency has its own entry. Failures are not cached.\n */\nclass CachingRateProvider {\n  constructor(inner, ttlMs, now = () => Date.now()) {\n    this.inner = inner;\n    this.ttlMs = ttlMs;\n    this.now = now;\n  }\n\n  getRate(currency) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n\n/**\n * Virtual (lazy) proxy: creates the real provider with `factory` on the first getRate() call, only once.\n * When the factory throws, the next call tries again.\n */\nclass LazyRateProvider {\n  constructor(factory) {\n    this.factory = factory;\n  }\n\n  getRate(currency) {\n    // TODO\n    throw new Error('Not implemented');\n  }\n}\n","testCount":8,"tests":"function fakeBank(rates) {\n  const bank = {\n    calls: [],\n    getRate(currency) {\n      bank.calls.push(currency);\n      if (!(currency in rates)) throw new Error('Unknown currency: ' + currency);\n      return rates[currency];\n    },\n  };\n  return bank;\n}\n\nfunction fakeClock() {\n  const clock = { t: 0, now: () => clock.t };\n  return clock;\n}\n\ntest('the caching proxy returns the real rate and asks the bank once', () => {\n  const bank = fakeBank({ EUR: 4.3 });\n  const rates = new CachingRateProvider(bank, 60000, fakeClock().now);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(bank.calls).toEqual(['EUR']);\n});\n\ntest('every currency is cached separately', () => {\n  const bank = fakeBank({ EUR: 4.3, USD: 3.9 });\n  const rates = new CachingRateProvider(bank, 60000, fakeClock().now);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('USD')).toBe(3.9);\n  rates.getRate('EUR');\n  rates.getRate('USD');\n  expect(bank.calls).toEqual(['EUR', 'USD']);\n});\n\ntest('an entry expires after the TTL', () => {\n  const table = { EUR: 4.3 };\n  const bank = fakeBank(table);\n  const clock = fakeClock();\n  const rates = new CachingRateProvider(bank, 60000, clock.now);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  table.EUR = 4.35;\n  clock.t = 59999;\n  expect(rates.getRate('EUR')).toBe(4.3);\n  clock.t = 60000;\n  expect(rates.getRate('EUR')).toBe(4.35);\n  expect(bank.calls).toHaveLength(2);\n});\n\ntest('the TTL counts from the latest fetch', () => {\n  const bank = fakeBank({ EUR: 4.3 });\n  const clock = fakeClock();\n  const rates = new CachingRateProvider(bank, 60000, clock.now);\n  rates.getRate('EUR');\n  clock.t = 60000;\n  rates.getRate('EUR');\n  clock.t = 100000;\n  rates.getRate('EUR');\n  expect(bank.calls).toHaveLength(2);\n  clock.t = 120000;\n  rates.getRate('EUR');\n  expect(bank.calls).toHaveLength(3);\n});\n\ntest('failures are not cached', () => {\n  const flaky = {\n    attempts: 0,\n    getRate() {\n      this.attempts++;\n      if (this.attempts === 1) throw new Error('Bank API timeout');\n      return 4.3;\n    },\n  };\n  const rates = new CachingRateProvider(flaky, 60000, fakeClock().now);\n  expect(() => rates.getRate('EUR')).toThrow('Bank API timeout');\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(rates.getRate('EUR')).toBe(4.3);\n  expect(flaky.attempts).toBe(2);\n});\n\ntest('the lazy proxy creates the real provider on first use, only once', () => {\n  let created = 0;\n  const lazy = new LazyRateProvider(() => {\n    created++;\n    return fakeBank({ EUR: 4.3 });\n  });\n  expect(created).toBe(0);\n  expect(lazy.getRate('EUR')).toBe(4.3);\n  expect(lazy.getRate('EUR')).toBe(4.3);\n  expect(created).toBe(1);\n});\n\ntest('a failed creation is retried on the next call', () => {\n  let created = 0;\n  const lazy = new LazyRateProvider(() => {\n    created++;\n    if (created === 1) throw new Error('Connection refused');\n    return fakeBank({ EUR: 4.3 });\n  });\n  expect(() => lazy.getRate('EUR')).toThrow('Connection refused');\n  expect(lazy.getRate('EUR')).toBe(4.3);\n  expect(created).toBe(2);\n});\n\ntest('proxies share the interface of the real provider, so they stack', () => {\n  const quote = (provider, currency, amount) => Math.round(amount * provider.getRate(currency) * 100) / 100;\n  let bank = null;\n  const stacked = new CachingRateProvider(\n    new LazyRateProvider(() => (bank = fakeBank({ EUR: 4.3 }))),\n    60000,\n    fakeClock().now,\n  );\n  expect(bank).toBeNull();\n  expect(quote(stacked, 'EUR', 100)).toBe(430);\n  expect(quote(stacked, 'EUR', 10)).toBe(43);\n  expect(bank.calls).toEqual(['EUR']);\n});\n"},{"lang":"python","runner":"browser","starter":"import time\nfrom abc import ABC, abstractmethod\nfrom typing import Callable\n\n\nclass RateProvider(ABC):\n    \"\"\"The subject: the real implementation calls the bank's slow API.\"\"\"\n\n    @abstractmethod\n    def get_rate(self, currency: str) -> float: ...\n\n\nclass CachingRateProvider(RateProvider):\n    \"\"\"Caching proxy: returns a cached rate while it is younger than ttl_ms (now() - fetched_at < ttl_ms),\n    otherwise asks `inner` again. Every currency has its own entry. Failures are not cached.\"\"\"\n\n    def __init__(self, inner: RateProvider, ttl_ms: float, now: Callable[[], float] | None = None):\n        self.inner = inner\n        self.ttl_ms = ttl_ms\n        self.now = now or (lambda: time.monotonic() * 1000)\n\n    def get_rate(self, currency: str) -> float:\n        # TODO\n        raise NotImplementedError\n\n\nclass LazyRateProvider(RateProvider):\n    \"\"\"Virtual (lazy) proxy: creates the real provider with `factory` on the first get_rate() call, only once.\n    When the factory raises, the next call tries again.\"\"\"\n\n    def __init__(self, factory: Callable[[], RateProvider]):\n        self.factory = factory\n\n    def get_rate(self, currency: str) -> float:\n        # TODO\n        raise NotImplementedError\n","testCount":8,"tests":"class FakeBank(RateProvider):\n    def __init__(self, rates):\n        self.rates = rates\n        self.calls = []\n\n    def get_rate(self, currency):\n        self.calls.append(currency)\n        if currency not in self.rates:\n            raise KeyError(currency)\n        return self.rates[currency]\n\n\nclass FakeClock:\n    def __init__(self):\n        self.t = 0\n\n    def now(self):\n        return self.t\n\n\ndef test_the_caching_proxy_returns_the_real_rate_and_asks_the_bank_once():\n    bank = FakeBank({\"EUR\": 4.3})\n    rates = CachingRateProvider(bank, 60000, FakeClock().now)\n    for _ in range(3):\n        got = rates.get_rate(\"EUR\")\n        assert got == 4.3, f\"expected 4.3, got {got}\"\n    assert bank.calls == [\"EUR\"], f\"expected one call, got {bank.calls}\"\n\n\ndef test_every_currency_is_cached_separately():\n    bank = FakeBank({\"EUR\": 4.3, \"USD\": 3.9})\n    rates = CachingRateProvider(bank, 60000, FakeClock().now)\n    assert rates.get_rate(\"EUR\") == 4.3\n    assert rates.get_rate(\"USD\") == 3.9\n    rates.get_rate(\"EUR\")\n    rates.get_rate(\"USD\")\n    assert bank.calls == [\"EUR\", \"USD\"], f\"got {bank.calls}\"\n\n\ndef test_an_entry_expires_after_the_ttl():\n    bank = FakeBank({\"EUR\": 4.3})\n    clock = FakeClock()\n    rates = CachingRateProvider(bank, 60000, clock.now)\n    assert rates.get_rate(\"EUR\") == 4.3\n    bank.rates[\"EUR\"] = 4.35\n    clock.t = 59999\n    got = rates.get_rate(\"EUR\")\n    assert got == 4.3, f\"still cached at 59 999 ms, got {got}\"\n    clock.t = 60000\n    got = rates.get_rate(\"EUR\")\n    assert got == 4.35, f\"expired at 60 000 ms, got {got}\"\n    assert len(bank.calls) == 2, f\"got {bank.calls}\"\n\n\ndef test_the_ttl_counts_from_the_latest_fetch():\n    bank = FakeBank({\"EUR\": 4.3})\n    clock = FakeClock()\n    rates = CachingRateProvider(bank, 60000, clock.now)\n    rates.get_rate(\"EUR\")\n    clock.t = 60000\n    rates.get_rate(\"EUR\")\n    clock.t = 100000\n    rates.get_rate(\"EUR\")\n    assert len(bank.calls) == 2, f\"expected 2 calls, got {len(bank.calls)}\"\n    clock.t = 120000\n    rates.get_rate(\"EUR\")\n    assert len(bank.calls) == 3, f\"expected 3 calls, got {len(bank.calls)}\"\n\n\ndef test_failures_are_not_cached():\n    class Flaky(RateProvider):\n        attempts = 0\n\n        def get_rate(self, currency):\n            self.attempts += 1\n            if self.attempts == 1:\n                raise TimeoutError(\"Bank API timeout\")\n            return 4.3\n\n    flaky = Flaky()\n    rates = CachingRateProvider(flaky, 60000, FakeClock().now)\n    with raises(TimeoutError):\n        rates.get_rate(\"EUR\")\n    assert rates.get_rate(\"EUR\") == 4.3\n    assert rates.get_rate(\"EUR\") == 4.3\n    assert flaky.attempts == 2, f\"expected 2 attempts, got {flaky.attempts}\"\n\n\ndef test_the_lazy_proxy_creates_the_real_provider_on_first_use_only_once():\n    created = []\n\n    def factory():\n        created.append(1)\n        return FakeBank({\"EUR\": 4.3})\n\n    lazy = LazyRateProvider(factory)\n    assert len(created) == 0, \"nothing should be created before the first call\"\n    assert lazy.get_rate(\"EUR\") == 4.3\n    assert lazy.get_rate(\"EUR\") == 4.3\n    assert len(created) == 1, f\"expected one creation, got {len(created)}\"\n\n\ndef test_a_failed_creation_is_retried_on_the_next_call():\n    created = []\n\n    def factory():\n        created.append(1)\n        if len(created) == 1:\n            raise ConnectionError(\"Connection refused\")\n        return FakeBank({\"EUR\": 4.3})\n\n    lazy = LazyRateProvider(factory)\n    with raises(ConnectionError):\n        lazy.get_rate(\"EUR\")\n    assert lazy.get_rate(\"EUR\") == 4.3\n    assert len(created) == 2, f\"expected 2 creations, got {len(created)}\"\n\n\ndef test_proxies_share_the_interface_of_the_real_provider_so_they_stack():\n    def quote(provider: RateProvider, currency, amount):\n        return round(amount * provider.get_rate(currency), 2)\n\n    banks = []\n\n    def factory():\n        banks.append(FakeBank({\"EUR\": 4.3}))\n        return banks[-1]\n\n    stacked = CachingRateProvider(LazyRateProvider(factory), 60000, FakeClock().now)\n    assert isinstance(stacked, RateProvider)\n    assert banks == [], \"the lazy proxy must not create the bank yet\"\n    assert quote(stacked, \"EUR\", 100) == 430\n    assert quote(stacked, \"EUR\", 10) == 43\n    assert banks[0].calls == [\"EUR\"], f\"got {banks[0].calls}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\n/// <summary>The subject: the real implementation calls the bank's slow API.</summary>\npublic interface IRateProvider\n{\n    decimal GetRate(string currency);\n}\n\n/// <summary>\n/// Caching proxy: returns a cached rate while it is younger than ttl (now - fetchedAt &lt; ttl),\n/// otherwise asks the inner provider again. Every currency has its own entry. Failures are not cached.\n/// </summary>\npublic class CachingRateProvider : IRateProvider\n{\n    private readonly IRateProvider inner;\n    private readonly TimeSpan ttl;\n    private readonly Func<DateTime> clock;\n\n    public CachingRateProvider(IRateProvider inner, TimeSpan ttl, Func<DateTime> clock = null)\n    {\n        this.inner = inner;\n        this.ttl = ttl;\n        this.clock = clock ?? (() => DateTime.UtcNow);\n    }\n\n    public decimal GetRate(string currency)\n    {\n        // TODO\n        throw new NotImplementedException();\n    }\n}\n\n/// <summary>\n/// Virtual (lazy) proxy: creates the real provider with the factory on the first GetRate call, only once.\n/// When the factory throws, the next call tries again.\n/// </summary>\npublic class LazyRateProvider : IRateProvider\n{\n    private readonly Func<IRateProvider> factory;\n\n    public LazyRateProvider(Func<IRateProvider> factory)\n    {\n        this.factory = factory;\n    }\n\n    public decimal GetRate(string currency)\n    {\n        // TODO\n        throw new NotImplementedException();\n    }\n}\n","testCount":8},{"lang":"java","runner":"judge0","starter":"import java.util.function.LongSupplier;\nimport java.util.function.Supplier;\n\n/** The subject: the real implementation calls the bank's slow API. */\ninterface RateProvider {\n    double getRate(String currency);\n}\n\n/**\n * Caching proxy: returns a cached rate while it is younger than ttlMillis (now - fetchedAt < ttlMillis),\n * otherwise asks the inner provider again. Every currency has its own entry. Failures are not cached.\n */\nclass CachingRateProvider implements RateProvider {\n    private final RateProvider inner;\n    private final long ttlMillis;\n    private final LongSupplier clock;\n\n    CachingRateProvider(RateProvider inner, long ttlMillis, LongSupplier clock) {\n        this.inner = inner;\n        this.ttlMillis = ttlMillis;\n        this.clock = clock;\n    }\n\n    CachingRateProvider(RateProvider inner, long ttlMillis) {\n        this(inner, ttlMillis, System::currentTimeMillis);\n    }\n\n    @Override\n    public double getRate(String currency) {\n        // TODO\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n\n/**\n * Virtual (lazy) proxy: creates the real provider with the factory on the first getRate call, only once.\n * When the factory throws, the next call tries again.\n */\nclass LazyRateProvider implements RateProvider {\n    private final Supplier<RateProvider> factory;\n\n    LazyRateProvider(Supplier<RateProvider> factory) {\n        this.factory = factory;\n    }\n\n    @Override\n    public double getRate(String currency) {\n        // TODO\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":8},{"lang":"go","runner":"judge0","starter":"package main\n\nimport \"time\"\n\n// RateProvider is the subject: the real implementation calls the bank's slow API.\ntype RateProvider interface {\n\tRate(currency string) (float64, error)\n}\n\n// CachingRateProvider is a caching proxy: it returns a cached rate while it is younger than ttl\n// (now - fetchedAt < ttl), otherwise it asks inner again. Every currency has its own entry.\n// Failures are not cached.\ntype CachingRateProvider struct {\n\tinner RateProvider\n\tttl   time.Duration\n\tnow   func() time.Time\n\t// TODO: the cache\n}\n\n// NewCachingRateProvider wraps inner; a nil now means time.Now.\nfunc NewCachingRateProvider(inner RateProvider, ttl time.Duration, now func() time.Time) *CachingRateProvider {\n\tif now == nil {\n\t\tnow = time.Now\n\t}\n\treturn &CachingRateProvider{inner: inner, ttl: ttl, now: now}\n}\n\n// Rate implements RateProvider.\nfunc (c *CachingRateProvider) Rate(currency string) (float64, error) {\n\t// TODO\n\treturn 0, nil\n}\n\n// LazyRateProvider is a virtual proxy: it creates the real provider with factory on the first Rate call,\n// only once. When the factory fails, the next call tries again.\ntype LazyRateProvider struct {\n\tfactory func() (RateProvider, error)\n}\n\n// NewLazyRateProvider does not call the factory yet.\nfunc NewLazyRateProvider(factory func() (RateProvider, error)) *LazyRateProvider {\n\treturn &LazyRateProvider{factory: factory}\n}\n\n// Rate implements RateProvider.\nfunc (l *LazyRateProvider) Rate(currency string) (float64, error) {\n\t// TODO\n\treturn 0, nil\n}\n","testCount":8}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.583Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"RateProvider","marks":[{"type":"code"}]},{"type":"text","text":" interface with "},{"type":"text","text":"getRate(currency)","marks":[{"type":"code"}]},{"type":"text","text":" – and that should stay so. The answer is the "},{"type":"text","text":"Proxy","marks":[{"type":"bold"}]},{"type":"text","text":" pattern: objects with the same interface that stand in front of the real provider and control access to it."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"CachingRateProvider(inner, ttl, now)","marks":[{"type":"code"}]},{"type":"text","text":" – a caching proxy:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"returns the cached rate while the entry is younger than its lifetime ("},{"type":"text","text":"now() - fetchedAt < ttl","marks":[{"type":"code"}]},{"type":"text","text":"), then asks "},{"type":"text","text":"inner","marks":[{"type":"code"}]},{"type":"text","text":" again;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"every currency has its own entry and the lifetime counts from the "},{"type":"text","text":"latest","marks":[{"type":"bold"}]},{"type":"text","text":" fetch;"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"provider errors reach the caller and are "},{"type":"text","text":"not cached","marks":[{"type":"bold"}]},{"type":"text","text":" – the next call asks the bank again."}]}]}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"LazyRateProvider(factory)","marks":[{"type":"code"}]},{"type":"text","text":" – a virtual (lazy) proxy: "},{"type":"text","text":"factory","marks":[{"type":"code"}]},{"type":"text","text":" creates the real provider only on the first "},{"type":"text","text":"getRate","marks":[{"type":"code"}]},{"type":"text","text":", and only once. When the factory throws, the next call tries again."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Both proxies implement "},{"type":"text","text":"RateProvider","marks":[{"type":"code"}]},{"type":"text","text":", so they can be "},{"type":"text","text":"nested","marks":[{"type":"bold"}]},{"type":"text","text":": "},{"type":"text","text":"CachingRateProvider(LazyRateProvider(factory), …)","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The clock is injected so the tests can move time: a function returning milliseconds (TypeScript, JavaScript, Python, Java – a "},{"type":"text","text":"LongSupplier","marks":[{"type":"code"}]},{"type":"text","text":"), a "},{"type":"text","text":"Func<DateTime>","marks":[{"type":"code"}]},{"type":"text","text":" with a "},{"type":"text","text":"TimeSpan ttl","marks":[{"type":"code"}]},{"type":"text","text":" (C#) and a "},{"type":"text","text":"func() time.Time","marks":[{"type":"code"}]},{"type":"text","text":" with a "},{"type":"text","text":"time.Duration","marks":[{"type":"code"}]},{"type":"text","text":" (Go). In Go the method is "},{"type":"text","text":"Rate(currency) (float64, error)","marks":[{"type":"code"}]},{"type":"text","text":", in Python "},{"type":"text","text":"get_rate","marks":[{"type":"code"}]},{"type":"text","text":", in C# "},{"type":"text","text":"GetRate","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"callout","attrs":{"variant":"warning","title":"Mind the ready-made classes"},"content":[{"type":"paragraph","content":[{"type":"text","text":".NET's "},{"type":"text","text":"Lazy<T>","marks":[{"type":"code"}]},{"type":"text","text":" in its default mode caches the factory's exception forever – the retry test will catch it. It is just as easy to cache an error by accident in the caching proxy."}]}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3d80884893657cc9fb","slug":"proxy","title":"Proxy – a stand-in that controls access to the real object"},{"id":"6b08bd3280884893657cc938","slug":"decorator","title":"Decorator – adding behaviour layer by layer"}],"topicsInfo":[{"slug":"proxy","title":"Proxy","group":"structural","icon":"shield"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:26.585Z","updatedAt":"2026-11-27T08:22:26.585Z"}