Caching

suggest change

A cache stores the result of an expensive operation (a computation, a database query, an HTTP request) so the next request for the same data can be answered without redoing the work.

Dart has no built-in cache class, but the core library gives you everything needed to build one: Map (which is an insertion-ordered LinkedHashMap by default), Future, late fields and Expando. For async work, the async package adds AsyncMemoizer and AsyncCache.

This article covers:

For a cache shared between several processes or servers, see Redis.

Memoizing a function

The simplest cache is a Map from arguments to results. putIfAbsent runs the callback only when the key is missing:

R Function(A) memoize<A, R>(R Function(A) f) {
  final cache = <A, R>{};
  return (A arg) => cache.putIfAbsent(arg, () => f(arg));
}

int slowSquare(int n) {
  print('computing $n * $n');
  return n * n;
}

void main() {
  final square = memoize(slowSquare);

  print(square(4));
  print(square(4));
  print(square(5));
}

Output:

computing 4 * 4
16
16
computing 5 * 5
25

The cache lives inside the closure, so it's private to the memoized function and freed together with it.

Only memoize pure functions: the result must depend only on the arguments. The key must also have proper == and hashCode. Numbers, strings, records and const objects work out of the box; for your own classes see Equality and comparison. Records are a convenient way to memoize functions with several arguments:

final _distanceCache = <(int, int), double>{};

double distance(int x, int y) =>
    _distanceCache.putIfAbsent((x, y), () {
      print('computing distance for ($x, $y)');
      return (x * x + y * y).toDouble();
    });

void main() {
  print(distance(3, 4));
  print(distance(3, 4));
}

Output:

computing distance for (3, 4)
25.0
25.0

Recursive functions

The documentation of Map.putIfAbsent says the callback must not add or remove keys from the map. A recursive memoized function does exactly that, so use an explicit lookup instead:

final _fibCache = <int, int>{0: 0, 1: 1};

int fib(int n) {
  final cached = _fibCache[n];
  if (cached != null) return cached;

  final result = fib(n - 1) + fib(n - 2);
  _fibCache[n] = result;
  return result;
}

void main() {
  print(fib(50));
  print(fib(90));
}

Output:

12586269025
2880067194370816120

Without the cache, fib(50) makes billions of calls. With it, each value is computed once.

Lazy fields with late final

Often you want to cache a value computed from an object's fields. A late final field with an initializer runs that initializer the first time the field is read and stores the result:

class Document {
  Document(this.text);

  final String text;

  late final int wordCount = _countWords();

  int _countWords() {
    print('counting words');
    return text.split(RegExp(r'\s+')).where((w) => w.isNotEmpty).length;
  }
}

void main() {
  final doc = Document('the quick brown fox jumps over the lazy dog');
  print('created');
  print(doc.wordCount);
  print(doc.wordCount);
}

Output:

created
counting words
9
9

This only works when the inputs never change. If text were mutable, the cached wordCount would go stale.

Attaching cached data to objects you don't own with Expando

If you can't add a field to a class (it comes from another package), an Expando lets you attach extra data to individual objects. The entry is kept only as long as the object is alive, so the cache can't leak memory:

class Image {
  Image(this.bytes);
  final List<int> bytes;
}

final _checksums = Expando<int>('checksum');

int checksum(Image image) => _checksums[image] ??= _compute(image.bytes);

int _compute(List<int> bytes) {
  print('computing checksum of ${bytes.length} bytes');
  return bytes.fold(0, (sum, b) => (sum * 31 + b) & 0xFFFFFFFF);
}

void main() {
  final image = Image([1, 2, 3, 4]);
  print(checksum(image));
  print(checksum(image));
}

Output:

computing checksum of 4 bytes
31810
31810

Expando keys can't be strings, numbers, booleans, records or null. For other kinds of weak caches see WeakReference in Memory and garbage collection.

Caching futures

When the expensive operation is asynchronous, cache the Future, not the value. If you cache only the finished value, several callers that ask at the same time all see an empty cache and all start their own request (a "cache stampede"). Storing the Future immediately makes later callers wait for the same in-flight request:

class FutureCache<K, V> {
  final _futures = <K, Future<V>>{};

  Future<V> get(K key, Future<V> Function(K key) loader) async {
    final cached = _futures[key];
    if (cached != null) return cached;

    final future = loader(key);
    _futures[key] = future;
    try {
      return await future;
    } catch (_) {
      // Don't cache failures: the next call will retry.
      _futures.remove(key);
      rethrow;
    }
  }

  void invalidate(K key) => _futures.remove(key);
}

Future<String> loadUser(int id) async {
  print('loading user $id');
  await Future.delayed(const Duration(milliseconds: 100));
  return 'User #$id';
}

Future<void> main() async {
  final users = FutureCache<int, String>();

  final results = await Future.wait([
    users.get(1, loadUser),
    users.get(1, loadUser),
    users.get(2, loadUser),
  ]);
  print(results);

  print(await users.get(1, loadUser));
}

Output:

loading user 1
loading user 2
[User #1, User #1, User #2]
User #1

Three concurrent calls caused only two loads. The code before the first await in an async function runs synchronously, so the second get(1, ...) already finds the future stored by the first one.

Removing a failed future is important. Otherwise a single network hiccup would be cached forever and every later caller would get the same exception.

Expiring entries (TTL)

Data from a database or remote API changes over time. A time-to-live (TTL) cache stores an expiration time with each entry and treats expired entries as missing:

class _Entry<V> {
  _Entry(this.value, this.expiresAt);
  final V value;
  final DateTime expiresAt;
}

class TtlCache<K, V> {
  TtlCache(this.ttl, {DateTime Function()? clock}) : _now = clock ?? DateTime.now;

  final Duration ttl;
  final DateTime Function() _now;
  final _entries = <K, _Entry<V>>{};

  V? get(K key) {
    final entry = _entries[key];
    if (entry == null) return null;
    if (!_now().isBefore(entry.expiresAt)) {
      _entries.remove(key);
      return null;
    }
    return entry.value;
  }

  void set(K key, V value) {
    _entries[key] = _Entry(value, _now().add(ttl));
  }

  void remove(K key) => _entries.remove(key);

  /// Drops all expired entries. Call it periodically for long-lived caches.
  void purgeExpired() {
    final now = _now();
    _entries.removeWhere((_, e) => !now.isBefore(e.expiresAt));
  }

  int get length => _entries.length;
}

The clock is a parameter so tests can control time instead of sleeping:

void main() {
  var now = DateTime.utc(2026, 1, 1, 12, 0);
  final cache = TtlCache<String, double>(
    const Duration(minutes: 5),
    clock: () => now,
  );

  cache.set('EUR/USD', 1.08);
  print(cache.get('EUR/USD'));

  now = now.add(const Duration(minutes: 4));
  print(cache.get('EUR/USD'));

  now = now.add(const Duration(minutes: 2));
  print(cache.get('EUR/USD'));
  print(cache.length);
}

Output:

1.08
1.08
null
0

Expired entries are removed lazily when someone reads them. In a long-running server, keys that are never read again stay in memory, so either call purgeExpired() from a Timer.periodic or bound the size of the cache as shown next.

Bounding size with an LRU cache

An unbounded cache is a memory leak with a nice name. A least-recently-used (LRU) cache keeps at most capacity entries and evicts the entry that wasn't used for the longest time.

Dart's default Map is a LinkedHashMap that remembers insertion order. Removing a key and inserting it again moves it to the end, so the first key is always the least recently used one:

class LruCache<K, V> {
  LruCache(this.capacity) : assert(capacity > 0);

  final int capacity;
  final _map = <K, V>{};

  V? get(K key) {
    if (!_map.containsKey(key)) return null;
    // Move to the end (most recently used).
    final value = _map.remove(key) as V;
    _map[key] = value;
    return value;
  }

  void set(K key, V value) {
    _map.remove(key);
    _map[key] = value;
    if (_map.length > capacity) {
      _map.remove(_map.keys.first);
    }
  }

  Iterable<K> get keys => _map.keys;
}

void main() {
  final cache = LruCache<String, int>(2);

  cache.set('a', 1);
  cache.set('b', 2);
  cache.get('a'); // 'a' is now the most recently used
  cache.set('c', 3); // evicts 'b'

  print(cache.keys);
  print(cache.get('b'));
  print(cache.get('a'));
}

Output:

(a, c)
null
1

All operations are O(1). containsKey before remove is needed so the cache also works correctly when V is nullable and a stored value is null.

To get both a size limit and expiration, store _Entry<V> values (from the TTL example) in an LruCache<K, _Entry<V>> and check expiresAt in get.

AsyncMemoizer and AsyncCache from package:async

The async package, maintained by the Dart team, has two ready-made helpers. Add it to pubspec.yaml:

dependencies:
  async: ^2.13.0

Run once: AsyncMemoizer

AsyncMemoizer runs an async computation at most once and returns the same future on every call. It's a good fit for one-time initialization, like opening a database connection:

import 'package:async/async.dart';

class Database {
  Database._();

  static Future<Database> open() async {
    print('opening database');
    await Future.delayed(const Duration(milliseconds: 50));
    return Database._();
  }
}

final _dbMemo = AsyncMemoizer<Database>();

Future<Database> get database => _dbMemo.runOnce(Database.open);

Future<void> main() async {
  final a = await database;
  final b = await database;
  print(identical(a, b));
  print(_dbMemo.hasRun);
}

Output:

opening database
true
true

Unlike FutureCache above, AsyncMemoizer also remembers errors: if the first run fails, every later call gets the same error.

Cache for a duration: AsyncCache

AsyncCache<T>(duration) caches the result of a callback for the given duration. Calls made while a fetch is in progress share the pending future. invalidate() forces the next fetch to call the callback again:

import 'package:async/async.dart';

final _configCache = AsyncCache<Map<String, Object>>(const Duration(minutes: 10));

Future<Map<String, Object>> loadConfig() => _configCache.fetch(() async {
      print('fetching config');
      await Future.delayed(const Duration(milliseconds: 50));
      return {'theme': 'dark', 'pageSize': 20};
    });

Future<void> main() async {
  await Future.wait([loadConfig(), loadConfig()]);
  print(await loadConfig());

  _configCache.invalidate();
  print(await loadConfig());
}

Output:

fetching config
{theme: dark, pageSize: 20}
fetching config
{theme: dark, pageSize: 20}

AsyncCache.ephemeral() only deduplicates concurrent calls: the value is forgotten as soon as the future completes. This is useful for "refresh" buttons that shouldn't start a second request while the first one is still running.

An AsyncCache holds a single value. For per-key caching, keep a Map<K, AsyncCache<V>> or use the FutureCache / TtlCache classes from this article.

HTTP caching

For HTTP, caching is usually done with standard headers rather than in application code.

Server side: Cache-Control and ETag

With Shelf, set Cache-Control to tell browsers and proxies how long a response may be reused, and ETag so clients can cheaply ask "has this changed?":

dependencies:
  shelf: ^1.4.2
  crypto: ^3.0.6
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as io;

Response productsHandler(Request request) {
  final body = jsonEncode([
    {'id': 1, 'name': 'Keyboard'},
    {'id': 2, 'name': 'Mouse'},
  ]);
  final etag = '"${sha1.convert(utf8.encode(body))}"';

  if (request.headers['if-none-match'] == etag) {
    // Client already has this version: send no body.
    return Response.notModified(headers: {'etag': etag});
  }

  return Response.ok(body, headers: {
    'content-type': 'application/json',
    'cache-control': 'public, max-age=60',
    'etag': etag,
  });
}

Future<void> main() async {
  final server = await io.serve(productsHandler, 'localhost', 8080);
  print('Listening on http://${server.address.host}:${server.port}');
}

Test it with curl:

$ curl -i http://localhost:8080/
HTTP/1.1 200 OK
cache-control: public, max-age=60
etag: "5d2c...e1"
...

$ curl -i -H 'If-None-Match: "5d2c...e1"' http://localhost:8080/
HTTP/1.1 304 Not Modified
etag: "5d2c...e1"

Use private instead of public for responses that depend on the logged-in user, and no-store for data that must never be cached (such as tokens).

Client side: conditional requests with package:http

package:http doesn't cache anything by itself. A small wrapper can remember the ETag and body of each URL and send If-None-Match on the next request (see HTTP Request for basics):

import 'package:http/http.dart' as http;

class _CachedResponse {
  _CachedResponse(this.etag, this.body);
  final String etag;
  final String body;
}

class CachingClient {
  final _client = http.Client();
  final _cache = <Uri, _CachedResponse>{};

  Future<String> get(Uri url) async {
    final cached = _cache[url];
    final response = await _client.get(url, headers: {
      if (cached != null) 'If-None-Match': cached.etag,
    });

    if (response.statusCode == 304 && cached != null) {
      print('304: using cached body');
      return cached.body;
    }
    if (response.statusCode != 200) {
      throw http.ClientException('HTTP ${response.statusCode}', url);
    }

    final etag = response.headers['etag'];
    if (etag != null) _cache[url] = _CachedResponse(etag, response.body);
    return response.body;
  }

  void close() => _client.close();
}

Future<void> main() async {
  final client = CachingClient();
  final url = Uri.parse('http://localhost:8080/');
  try {
    print(await client.get(url));
    print(await client.get(url));
  } finally {
    client.close();
  }
}

Output against the server above:

[{"id":1,"name":"Keyboard"},{"id":2,"name":"Mouse"}]
304: using cached body
[{"id":1,"name":"Keyboard"},{"id":2,"name":"Mouse"}]

The second request still makes a round trip, but the server sends no body. To skip the request entirely, combine this with the TtlCache and honor max-age.

Cache invalidation

Every cache has to answer: "when is the cached value wrong?". Common strategies:

class UserRepository {
  UserRepository(this._db);

  final Map<int, String> _db; // stands in for a real database
  final _cache = TtlCache<int, String>(const Duration(minutes: 5));

  String? findName(int id) {
    final cached = _cache.get(id);
    if (cached != null) return cached;

    final name = _db[id];
    if (name != null) _cache.set(id, name);
    return name;
  }

  void rename(int id, String name) {
    _db[id] = name;
    _cache.remove(id); // next read loads the new value
  }
}

void main() {
  final repo = UserRepository({1: 'Alice'});
  print(repo.findName(1));
  repo.rename(1, 'Alicia');
  print(repo.findName(1));
}

Output:

Alice
Alicia

In-process caches are per isolate. If you run several server processes or isolates (see Isolates), each has its own copy and explicit invalidation only affects one of them. In that case use a shared cache such as Redis, or rely on short TTLs.

Best practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents