System Design Cases
PWA & Service Workers
PWA & Service Workers concept page: Service Worker as browser proxy for network requests, cache strategies (cache-first, network-first, stale-while-revalidate), Workbox library, manifest.json (installable), Push API + Notifications, Background Sync queue, offline-first patterns, PWA vs native trade-offs ADR. Four scenarios: SW intercepts fetch and chooses cache strategy, offline page when network down, push notification flow (tab closed), background sync queue.
PWA и Service Worker: event lifecycle, versioned caches и recovery
Service Worker — origin-scoped event-driven worker, который может перехватывать fetch и использовать Cache API. User agent может завершить worker между событиями; долговечное состояние нельзя держать только в памяти процесса.
Registration содержит installing, waiting и active workers. Успешный install не означает немедленный control уже открытых pages, а skipWaiting/clients.claim меняют rollout semantics и требуют совместимости со старыми clients.
Проверяемые утверждения
- ServiceWorkerGlobalScope доступен в secure context; localhost имеет специальные development allowances, но production требует HTTPS.
- event.waitUntil продлевает lifetime события; rejected install promise проваливает install. Асинхронную работу надо присоединять в допустимое event window.
- Cache API похож на response store, но не является HTTP cache и не имеет автоматической freshness/eviction policy приложения.
- Web App Manifest и Service Worker решают разные задачи: manifest описывает install/display metadata, worker реализует programmable network behavior.
Границы и компоненты
| Компонент | Роль в модели |
|---|---|
| Controlled Page | register and observe; controlled fetch; manifest discovery |
| Service Worker Registration | register and observe; install update |
| Installing or Waiting Worker | install update; precache version |
| Active Event Worker | controlled fetch; cache policy; network request; classified outcome |
| Versioned Cache Storage | precache version; cache policy |
| Network Origin | network request |
| Web App Manifest | manifest discovery |
| Offline and Update Telemetry | classified outcome |
Сценарии
Install a versioned app shell
A new worker opens a new cache namespace and precaches the minimal immutable shell inside install waitUntil. Any required fetch rejection fails the install and leaves the active version intact.
Проверяемый исход: The waiting worker is complete or absent; a partial cache is never promoted as a successful release.
Serve an offline navigation deliberately
The active worker receives a navigation fetch. It tries the network within policy, then returns a version-compatible offline document; API mutation failures are not replaced with fake success.
Проверяемый исход: Offline fallback is route/type aware, and the UI distinguishes cached content, unavailable data and queued intent.
Activate an update without mixed versions
A waiting worker activates after the old client set is safe to replace. Activate migration removes only caches not needed by any supported client, then new pages become controlled.
Проверяемый исход: HTML, chunks and data schema remain compatible during the transition; forced takeover is used only with a tested cross-version contract.
Recover from cache quota or corruption
A cache write rejects because of quota or storage failure. The worker classifies the failure, keeps network behavior correct and emits minimized telemetry instead of treating cache success as guaranteed.
Проверяемый исход: The request still follows a valid network/error path, cache repair is bounded, and the UI never claims durable offline availability without verification.
Failure, concurrency и evolution checklist
- Assume the worker can terminate between events. Persist durable state in browser storage and make each event handler restartable.
- Version caches and delete obsolete namespaces during a compatible activation phase, not while the old active worker still serves clients.
- Handle QuotaExceeded, missing/corrupt entries, opaque responses and network timeouts explicitly; cache.match miss is normal control flow.
- Test first visit offline, update with multiple open tabs, force refresh/bypass, storage eviction and a broken new worker.
Security и privacy
- Limit worker scope, serve script over HTTPS with appropriate cache/update headers, and prevent untrusted content from writing the worker script path.
- Do not broadly cache authenticated HTML/API responses. Partition and purge sensitive entries, and remember Cache Storage is readable by same-origin script.
- Validate every queued/replayed mutation at the server; a worker is client code and cannot grant authorization.
Метрики, формулы и допущения
cache_hit_ratio = policy_hits / eligible_fetches; separate navigation, immutable asset and API strategies instead of combining unlike denominators.offline_shell_bytes = Σ required_versioned_response_bytes + metadata_overhead; compare with measured quota and leave headroom for other origin storage.stale_age = response_time − origin_validation_time; a cache insertion timestamp is not necessarily the data creation time.- Update adoption is a distribution across controlled clients/tabs. One activated worker does not prove every open page uses the new release.
Числа и bounds выше действуют только при названных units, population и assumptions. Ни паттерн, ни browser API сами по себе не задают SLA, capacity или correctness.
Решения для production review
- Define a strategy per request class: network-only, cache-first immutable, network-first navigation, stale-while-revalidate, or explicit offline queue.
- Keep precache minimal and versioned; runtime cache growth needs quota and eviction policy.
- Choose update takeover semantics from compatibility evidence, not from a reflexive skipWaiting call.
Первичные и официальные источники
- https://www.w3.org/TR/service-workers/
- https://www.w3.org/TR/appmanifest/
- https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers
- https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria
Scope note
Диаграмма показывает standards-level lifecycle. Она не обещает install prompt, push delivery, Background Sync support, permanent browser storage или одинаковое PWA behavior на всех platforms.