Full answer
An optimistic update assumes success. The UI changes at once, so the app feels fast, and the app corrects itself if the request fails. It suits low-risk, high-success actions such as toggles, likes, and reordering. Do not use it for payments or actions with side effects the user must see confirmed.
Steps:
- Remember the previous value of the item.
- Apply the new value to the local signal immutably.
- Send the request.
- On success: optionally replace the item with the server's version (it may contain new fields such as
updatedAt). - On error: restore only that item to the remembered value, unless a newer change to the same item has happened since, and show a message with a retry option.
Concurrency problems:
- Rapid toggling sends several requests. Responses can arrive out of order. Use a counter per item: each change gets a number, and a response or rollback applies only if its number is still the latest for that item.
- Another approach is to serialise requests per item with
concatMap(see thegroupByitem), or to cancel the old request withswitchMapwhen the new value supersedes it. For toggles the final value is what matters, soswitchMapper item is natural, but the server may still have processed the cancelled request, so the server must be idempotent. - Roll back one item only, not the whole list snapshot, or you will undo unrelated changes made in the meantime.
Other points: do not rollback silently. Tell the user. Keep a visible "saving" or "failed" mark if the action may take long. Make the request idempotent (send the target value done: true, not "toggle"), so retries are safe. Test it with HttpTestingController for success, failure, and out-of-order responses.
// file: task.store.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, inject, signal } from '@angular/core';
export interface Task {
id: number;
title: string;
done: boolean;
}
@Injectable({ providedIn: 'root' })
export class TaskStore {
private readonly http = inject(HttpClient);
private readonly versions = new Map<number, number>();
readonly tasks = signal<Task[]>([
{ id: 1, title: 'Revise signals', done: false },
{ id: 2, title: 'Finish homework', done: false },
]);
readonly error = signal<string | null>(null);
setDone(id: number, done: boolean): void {
const previous = this.tasks().find((t) => t.id === id);
if (!previous) {
return;
}
const version = (this.versions.get(id) ?? 0) + 1;
this.versions.set(id, version);
this.error.set(null);
this.replace(id, { done });
this.http.patch<Task>(`/api/tasks/${id}`, { done }).subscribe({
next: (server) => {
if (this.versions.get(id) === version) {
this.replace(id, server); // server is the final truth for the latest request
}
},
error: () => {
if (this.versions.get(id) === version) {
this.replace(id, { done: previous.done });
this.error.set(`Could not update "${previous.title}". Please try again.`);
}
},
});
}
private replace(id: number, changes: Partial<Task>): void {
this.tasks.update((list) => list.map((t) => (t.id === id ? { ...t, ...changes } : t)));
}
}
// file: task.store.spec.ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { TaskStore } from './task.store';
describe('TaskStore optimistic update', () => {
let store: TaskStore;
let backend: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()] });
store = TestBed.inject(TaskStore);
backend = TestBed.inject(HttpTestingController);
});
afterEach(() => backend.verify());
it('updates at once and keeps the server value on success', () => {
store.setDone(1, true);
expect(store.tasks()[0].done).toBeTrue();
backend.expectOne('/api/tasks/1').flush({ id: 1, title: 'Revise signals', done: true });
expect(store.tasks()[0].done).toBeTrue();
expect(store.error()).toBeNull();
});
it('rolls back only that task on failure', () => {
store.setDone(1, true);
store.setDone(2, true);
backend.expectOne('/api/tasks/1').flush('', { status: 500, statusText: 'Server Error' });
backend.expectOne('/api/tasks/2').flush({ id: 2, title: 'Finish homework', done: true });
expect(store.tasks()[0].done).toBeFalse();
expect(store.tasks()[1].done).toBeTrue();
expect(store.error()).toContain('Revise signals');
});
it('ignores a stale failure when a newer change exists', () => {
store.setDone(1, true); // request A
store.setDone(1, false); // request B (newer)
const [a, b] = backend.match('/api/tasks/1');
b.flush({ id: 1, title: 'Revise signals', done: false });
a.flush('', { status: 500, statusText: 'Server Error' }); // late failure of A
expect(store.tasks()[0].done).toBeFalse();
expect(store.error()).toBeNull();
});
});Angular 20.3, strict check passes, and a Karma spec with `HttpTestingController` checks success, rollback, and a stale failure that must not roll back newer state.
Key points
- Apply the change locally first, then send the request. Roll back only the affected item on error.
- Track a version per item so late responses cannot overwrite newer state.
- Send the target value (idempotent), not "toggle".
- Tell the user about failures. Avoid optimistic updates for high-risk actions.
Common mistakes
- Restoring a whole-list snapshot, which undoes other changes.
- Sending "toggle" instead of the target value, so a retry flips it back.
- Ignoring out-of-order responses.
Follow-ups
- When would you choose pessimistic updates instead?
- How would you handle the user going offline?
- How is this different with a `resource`?
Tips
- Start with when optimistic updates are suitable.
- Describe the out-of-order problem before being asked.
- Say "idempotent" and explain it with an example.
Evaluation rubric
- Implements apply, send, and rollback correctly.
- Handles concurrency with versions or cancellation.
- Knows when the pattern fits.