idempotency
Client-side idempotency keys for Dart & Flutter.
Pair with any Stripe-style Idempotency-Key backend: every logical operation
gets a key that is created and persisted before the request fires and
reused for every retry — even across app restarts — so a flaky network can
never submit the same payment/order/booking twice.
Why
Servers that honor Idempotency-Key headers replay the stored response when
the same key arrives twice — but that only protects you if the client
sends the same key on every retry of one logical operation, and a new
key when the user genuinely submits again. Getting that right by hand means
solving three problems:
- Persist before you fire — a crash after generating the key but before the request must still reuse the key next launch.
- Retries reuse — transport failures retry with the identical key.
- New submissions rotate — the next real submission must not replay the old response.
This package is exactly that lifecycle, distilled. It pairs naturally with the author's server-side implementation, django-idem.
Usage
final idem = IdempotencyKeys(
store: (operation, key) => box.put(operation, key), // shared_preferences, hive, file…
load: (operation) => box.get(operation),
);
Future<Payment> pay(String cartId, double amount) async {
final operation = 'payment:$cartId';
final key = idem.keyFor(operation); // persisted before the request fires
try {
final response = await dio.post(
'/payments',
options: Options(headers: {'Idempotency-Key': key}),
data: {'amount': amount},
);
idem.complete(operation); // next submission gets a fresh key
return Payment.fromJson(response.data);
} on DioException catch (error) {
if (error.type == DioExceptionType.connectionError) {
rethrow; // transport failure → retry sends the SAME key
}
idem.complete(operation); // definitive failure → next submit is new
rethrow;
}
}
hasPendingAttempt(operation) tells you when a previous attempt may still be
unresolved on the server (e.g. show "processing your last submission…"
instead of a pay button after a crash-mid-request).
Testing
8 tests: persist-before-return, retry reuse (in-session and across
"restarts" via persistence), per-operation scoping, key rotation after
complete, pending-attempt detection from persisted state, and uniqueness
under rapid generation.
dart test
License
Libraries
- idempotency
- Client-side idempotency keys for Dart and Flutter.