DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

JavaScript

JavaScript (JS) is an object-oriented programming language that allows engineers to produce and implement complex features within web browsers. JavaScript is popular because of its versatility and is preferred as the primary choice unless a specific function is needed. In this Zone, we provide resources that cover popular JS frameworks, server applications, supported data types, and other useful topics for a front-end engineer.

icon
Latest Premium Content
Trend Report
Low-Code Development
Low-Code Development
Refcard #363
JavaScript Test Automation Frameworks
JavaScript Test Automation Frameworks
Refcard #288
Getting Started With Low-Code Development
Getting Started With Low-Code Development

DZone's Featured JavaScript Resources

PWA on iOS, Part 5: Service Worker Updates, Cache, and Push

PWA on iOS, Part 5: Service Worker Updates, Cache, and Push

By Konstantin Shkurko
A user opens your PWA on their iPhone. Late the night before, the team shipped a release: the cart format changed, a couple of API fields were renamed, and a local database migration was added. The phone spent the whole night on the charger, and nobody closed the app. Which version the user sees in the morning depends on a script they don't even know exists. A Service Worker (from here on, just "worker") is a separate piece of JavaScript that the browser places between the page and the network: the page asks for a file or some JSON, and the worker decides whether to serve it from local storage, fetch it from the internet, or do both at once. It has no window of its own, it can't reach the DOM or localStorage, and it lives in bursts, because WebKit wakes it up for a specific event and may stop it as soon as the event has been handled. Whatever can't be lost, a worker keeps in IndexedDB or on the server, and in memory it holds only what you can afford to lose. Most likely, that morning went like this. The old worker was already running and, within a fraction of a second, served yesterday's app shell from the cache without even asking the network. In parallel, the browser went to the server for sw.js, noticed the file had changed, and began installing a new version next to the old one. While the person scrolls through the list of orders, the fresh version sits downloaded, waiting its turn, and when that turn comes and what breaks along the way is decided by a few dozen lines in your sw.js. We covered registration, HTTPS, and scope in part two, and I won't repeat them: everything here begins at the point where register() has already done its job. Service Worker Lifecycle on iOS From Install to Fetch The browser compares the downloaded sw.js with the copy it already has, and if even one byte differs, it fires the install event on the new copy. This is the only moment when a worker can prepare in peace: download the app shell (HTML, the main CSS and JS, an offline page, a couple of icons) and put it into the Cache API. The event.waitUntil() call tells the browser that preparation is still going on, and if the promise passed to it rejects, the installation is considered failed: the new version is thrown away, and the old one keeps working as if nothing had happened. Here is the first trap. The cache.addAll() method is atomic: either all the files on the list end up in the cache, or none do, and a single 404 is enough to fail the entire installation. That is why the precache (the name for the cache that is filled at install time) holds only what the app can't launch without. Product photos, secondary fonts, and API responses are fetched later, separately, with error handling. After installation, the new worker usually enters the waiting state and waits. The reason is that the open page has already loaded the old JavaScript, and if the request handler suddenly changes underneath it, the old code will start receiving responses meant for the new one. The wait ends when all pages controlled by the previous version are closed. On the iPhone, that moment is hard to predict: an installed app can hang in the switcher for weeks, or it can be quietly unloaded by the system in the background, in which case the next tap on the icon will be a cold start already on the new version. When its turn comes, the new worker receives activate. By then the previous version is gone, which makes this a convenient place to delete its caches. Then the main work begins: every page request inside the scope (the part of the site the worker controls) becomes a fetch event, and if the handler called event.respondWith(), the response comes from it, while if it didn't, the request goes to the network the ordinary way. Here's a skeleton with installation and cleanup: JavaScript // sw.js; the build fills in the file list const PREFIX = 'warehouse-'; const SHELL = `${PREFIX}shell-v42`; const RUNTIME = `${PREFIX}runtime-v42`; const SHELL_FILES = ['/', '/offline.html', '/assets/app.3f9a1c.js', '/assets/app.77b2e0.css']; self.addEventListener('install', (event) => { event.waitUntil(caches.open(SHELL).then((cache) => cache.addAll(SHELL_FILES))); }); self.addEventListener('activate', (event) => { event.waitUntil((async () => { await self.registration.navigationPreload?.enable(); const names = await caches.keys(); await Promise.all( names .filter((name) => name.startsWith(PREFIX) && name !== SHELL && name !== RUNTIME) .map((name) => caches.delete(name)) ); })()); }); It's better not to maintain the SHELL_FILES list by hand. If the bundler changes the hash in a file name while the array stays the same, addAll gets a 404, the installation quietly fails, and users sit on the previous version until somebody notices that yesterday's fix never reached the iPhones. The prefix in the filter isn't there for show, either. A single origin (a combination of protocol, domain, and port) often hosts both a marketing site and an account area, each with its own caches, and cleanup on the principle of "delete everything that doesn't match my current name" will one day wipe out somebody else's precache. The navigationPreload line will come in handy a little later, when we get to cold starts. Why skipWaiting Breaks Apps With Data and Migrations Waiting is annoying, and many tutorials turn it off in two lines. self.skipWaiting() in install makes the new worker activate immediately, clients.claim() in activate takes over already open pages without a reload, and in a demo it looks great: you ship, refresh the tab, and everything is up to date. Back to the morning scene. The page on the warehouse worker's phone loaded yesterday's bundle, and that bundle lazily pulls in the order screen from /assets/order.8c1d.js. The new worker activated in the middle of the session, dutifully deleted the old cache in activate, and its own precache already holds order.51fa.js. The person taps an order, the old code asks for the old file, which is no longer in the cache, and if the phone happens to be offline at that moment, or the previous builds have already been removed from the CDN, a white screen appears instead of the order. The database has a similar story: the new worker opens IndexedDB with schema version 3, the open page holds a connection to version 2, and the migration runs into that connection. Both breakages arise because the new version interfered with a page that doesn't know about it yet. That's why, in apps with data, I leave the worker its right to wait, and below I'll show how to offer the update without getting a reload loop. I enable skipWaiting() together with clients.claim() only where there's nothing to break: documentation, a blog, a landing page, releases with strict backward compatibility. An app with data, migrations, and lazy chunks can wait until the person agrees to a reload on their own. How to Update a Service Worker Without a Reload Loop The scheme is simple. The page notices a worker in waiting, shows an unobtrusive banner, and when it's tapped, asks the worker to skip the wait; when control passes to the new version (the controllerchange event), the page reloads once. The word "once" is essential here: a careless implementation sends the app into an endless reload loop. Most often the loop is built like this: location.reload() hangs on controllerchange, and the worker calls skipWaiting() on its own, without being asked. If sw.js differs on every request (the server assembles it on the fly with a timestamp, or a proxy mixes something into the body), every reload brings one more "new" version, it activates immediately, the event arrives again, and the app reloads in circles. On an iPhone this looks like a flickering white screen where nothing can be tapped, and reproducing it on your own device is far from easy. A flag in sessionStorage breaks the loop: only a button press can set it, it's cleared before the reload, and the freshly opened page no longer reacts to the controller change. An in-memory variable is useless here, since the very reload it was meant to control wipes it out, while sessionStorage survives a reload and disappears only when the app is closed. JavaScript // app.js const reg = await navigator.serviceWorker.register('/sw.js'); function offerUpdate(worker) { showBanner('A new version is available. Unsent orders will be kept.', () => { sessionStorage.setItem('sw-reload', '1'); worker.postMessage({ type: 'SKIP_WAITING' }); }); } if (reg.waiting && navigator.serviceWorker.controller) offerUpdate(reg.waiting); reg.addEventListener('updatefound', () => { const next = reg.installing; next.addEventListener('statechange', () => { if (next.state === 'installed' && navigator.serviceWorker.controller) offerUpdate(next); }); }); navigator.serviceWorker.addEventListener('controllerchange', () => { if (sessionStorage.getItem('sw-reload') !== '1') return; sessionStorage.removeItem('sw-reload'); location.reload(); }); // sw.js self.addEventListener('message', (event) => { if (event.data?.type === 'SKIP_WAITING') self.skipWaiting(); if (event.data?.type === 'LOGOUT') { event.waitUntil(caches.keys().then((names) => Promise.all( names.filter((n) => n.startsWith(`${PREFIX}user-`)).map((n) => caches.delete(n)) ))); } }); showBanner here is your own function, and the scheme usually stumbles on the first installation. When a worker is installed for the first time, controller is still empty, and without that check a new user will be offered an update in the very first minute of getting to know the app. The text on the banner is as much a part of the decision as the code. The person doesn't need a lecture about workers; they need to know what will happen to what they were doing, hence the wording "A new version is available. Unsent orders will be kept." That sentence is true only if the queue lives in IndexedDB, because in-memory page state won't make it to the new version. For apps that stay open for hours, there is registration.update(). The browser checks sw.js on navigations anyway, but a single-page app that hasn't been reloaded once since morning may not learn about a release for a long time. I call update() when the app returns to the foreground, but no more than about once an hour. I serve sw.js itself with Cache-Control: no-cache, so the check doesn't run into the HTTP cache. Cache First, Network First and Stale-While-Revalidate on iOS The three classic strategies are easiest to remember by what each one promises the user. Choosing by file extension ("everything .js from the cache") sooner or later produces a screen that either lags or confidently shows yesterday's data. Cache First serves the local copy and goes to the network only when there is no copy. For files with a hash in the name, it's the best choice: app.3f9a1c.js will never change, a new build gets a new name, and keeping the old one for a year is safe. Fonts and icons go here as well. But /api/orders under Cache First will show an order in the state in which it was first cached, and will keep showing it. Network First goes to the network first and falls back to the stored copy if the network didn't answer. This is what I use for navigation, meaning the HTML documents themselves, and for lists where freshness matters more than speed, with one condition: the interface must be able to say honestly that the data shown was received at nine in the morning. Stale-While-Revalidate (literally "serve the stale one and recheck") answers from the cache instantly and at the same time requests a fresh version for next time. It suits avatars, the catalog, reference data, and feeds that can be shown one visit late. The first display may be stale, and that is part of the contract with the user, best settled with the product manager in advance. JavaScript self.addEventListener('fetch', (event) => { const { request } = event; const url = new URL(request.url); if (request.method !== 'GET' || url.origin !== self.location.origin) return; if (request.headers.has('range') || url.pathname.startsWith('/api/pay')) return; if (request.mode === 'navigate') event.respondWith(networkFirst(event)); else if (url.pathname.startsWith('/assets/')) event.respondWith(cacheFirst(event)); else if (url.pathname.startsWith('/api/catalog')) event.respondWith(staleWhileRevalidate(event)); }); function remember(request, response) { if (!response.ok) return Promise.resolve(); const copy = response.clone(); return caches.open(RUNTIME).then((cache) => cache.put(request, copy)).catch(() => {}); } async function cacheFirst(event) { const cached = await caches.match(event.request); if (cached) return cached; const response = await fetch(event.request); event.waitUntil(remember(event.request, response)); return response; } async function networkFirst(event) { try { const response = (await event.preloadResponse) ?? (await fetch(event.request)); event.waitUntil(remember(event.request, response)); return response; } catch { return (await caches.match(event.request)) ?? caches.match('/offline.html'); } } async function staleWhileRevalidate(event) { const cached = await caches.match(event.request); const fresh = fetch(event.request).then((response) => { event.waitUntil(remember(event.request, response)); return response; }); event.waitUntil(fresh.catch(() => {})); return cached ?? fresh; } A Response body is a stream, and it can be read exactly once: either the browser hands it to the page, or the Cache API writes it to disk. Hence response.clone(), and hence a subtle bug I've run into more than once in other people's code. The clone is made inside .then() after caches.open(), when the browser has already started reading the original, and you get a TypeError about a used body, and an intermittent one at that, because it all depends on who got there first. In remember, the clone is taken synchronously, before any waiting. The write itself is wrapped in event.waitUntil(): as soon as the response has been delivered, WebKit is entitled to stop the worker, and without that wrapper the background refresh in Stale-While-Revalidate sometimes simply doesn't happen. The response.ok check filters out everything that isn't 2xx. Without it, offline mode will one day open yesterday's "not found" page, and the person will decide the order was deleted. It's even worse if the server answers an error with an HTML page and a 200 status: the worker can't tell it apart from a normal response, and that gets fixed on the server. For navigations, the fallback here is: the same page from the cache, and if it isn't there, offline.html. For a single-page app that's not enough, because a direct entry via a link like /orders/42 without a network won't find such a document in the cache, and it's more correct to serve the cached shell at / and let the app itself decide what to show. A server-rendered site, on the contrary, must not be handed the shell for every address, or without a network every page turns into the home page. Navigation Preload and Cold Start in iOS PWAs The cold start on the iPhone is unpleasant: the system unloaded the app long ago, the person taps the icon, and before the HTML request can go out to the network, WebKit has to bring up the worker and execute its script, while the network sits idle all that time. Navigation preload, which appeared in Safari and iOS 15.4 in the spring of 2022, lets the browser start the navigation request in parallel with the worker's startup and hands the ready response over in event.preloadResponse. It's enabled by the line in activate from the first snippet, and networkFirst takes the preload response first. Such a request arrives at the server with the header Service-Worker-Navigation-Preload: true; the value can be changed via navigationPreload.setHeaderValue(), and if it wants to, the server can answer with a lightweight version of the page. There's a payoff where navigations go to the network anyway. If the shell is served by Cache First, preload becomes an extra request on every launch, one whose response nobody reads. Cache API Pitfalls With Opaque Responses and Personal Data An image from someone else's CDN without CORS headers reaches the worker as an opaque response: status 0, ok equals false, and the body and headers are invisible to the script. You can't tell a normal image from an error page in it. cache.add() and cache.addAll() refuse to save such responses, but cache.put() will accept them, and later, on a plane, the gallery will show whatever was stored, even if what was stored was an error. Our remember skips them because it checks ok. If third-party files are needed offline, the CDN must send Access-Control-Allow-Origin and the tag must get a crossorigin attribute; the other way is to proxy the files through your own origin. Let everything else load over a live network, with no attempt to fake an offline gallery. There is a myth about cache keys that turns up even in good articles: that any different request header turns a request into a different key. By the specification, caches.match() compares the URL and the method, and it takes request headers into account only if the stored response has a Vary header, and then only those listed in it. A response with Vary: * will be rejected by cache.put() outright. The query string matters far more: ?lang=en changes the meaning of the response and can't be ignored, while ?v=3f9a is a cache buster, for which there is the ignoreSearch: true option, although it's still better to keep the version in the file name. The most unpleasant property of the Cache API is that it is bound to an origin and knows nothing about your accounts. If the app caches /api/me or a particular employee's orders, then after signing out that JSON doesn't go anywhere, and the next person on a shared warehouse iPad will see someone else's data until the network responds. Personal responses I either don't put into the Cache API at all, or keep in a separate cache with a clear prefix such as warehouse-user- and delete it on sign-out. It's best to delete from both sides. The page sends the worker the message { type: 'LOGOUT' }, and the message handler from the updates section wipes the user caches. In parallel, the page itself walks through caches.keys() and deletes the same things, because the Cache API is available from the window too, and there may be no active worker at that moment, for example in the middle of installing a new version. An extra deletion costs nothing; a missed one costs you a leak of someone else's data. The backend can also break offline mode without touching a line of sw.js. Yesterday /api/feed was the same for everyone and lived happily in Stale-While-Revalidate; today the response depends on the role, and the cache starts handing the administrator's feed to the warehouse staff. For every route that lands in the runtime cache, I write down next to the API description who sees it, how stale it may get, and what to show without a network; "we cache all GETs" does not count as a policy. Workbox won't choose the policy for you either. It takes the routine out of precache revisions and standard strategies, but runtimeCaching: [{ urlPattern: /.*/, handler: 'CacheFirst' }] is still a bad idea, just written more briefly. iOS Storage Quota and Eviction in Safari 17 and Later Two numbers still circulate about iOS storage: "no more than 50 MB" and "everything gets wiped after seven days." Both are outdated or refer to a different situation. The seven-day rule came with ITP (Intelligent Tracking Prevention, Safari's protection against tracking) in March 2020 and concerned data that site scripts write inside Safari, whereas for apps on the Home Screen, WebKit introduced its own counter of days of use at the same time, and their data should not be deleted during normal use. The current policy is described in WebKit's "Updates to Storage Policy" post from August 2023 and has been in effect since Safari 17 and iOS 17. A single origin in a browser app (one that can be set as the default browser) is allowed up to 60% of the disk, in other apps with embedded web content up to 15%, and the overall cap across all sites is 80% and 20% respectively. An app launched from the Home Screen gets the same quotas as in the browser. Before Safari 17, an origin started with 1 GB, after which Safari asked the user for permission. Cookies and the HTTP cache don't count toward these quotas. Sixty percent of the disk sounds generous, but that is a ceiling. How much is actually available is shown by navigator.storage.estimate() (it's in Safari since version 17), and WebKit warns that it may change the quota depending on free space and how often the person visits the site, to make the number harder to use for device fingerprinting. WebKit evicts data per origin as a whole, starting with the ones used least recently. There are three triggers: the overall cap is exceeded, the device is running out of space, or the site hasn't been opened for a long time. Protected from this are origins with an open page and those that have been granted persistent storage mode. You can ask for that mode via navigator.storage.persist(), which exists since Safari 15.2. There won't be a dialog; WebKit decides on its own by heuristics, and the same post says one of them takes into account whether the site is open as a Home Screen app. I call persist() once after the first launch from the icon and don't attach much importance to the answer, because true means "we'll try not to touch it" and nothing beyond that. When quota runs out, a write fails with QuotaExceededError, and that applies to both cache.put() and IndexedDB transactions. The most insulting version of this error lives in the fetch handler. If await cache.put() sat inside the same try as the fetch in networkFirst, a full quota would send the person to yesterday's copy or the offline page with a fully working network. In remember, the write is moved into waitUntil and swallows the error with an empty catch, since the response matters more than the copy, and it's enough to log the error once per session. I wouldn't promise offline maps at all: there are endlessly many tiles, and the quota is finite. And don't drag heavy things into the precache, because a 40 MB catalog in addAll on an unstable network will fail the entire installation, and with it the app's update. Such data is loaded after startup, put into IndexedDB page by page, and the previous page is shown if the new one hasn't arrived. Video and Range Requests in a Service Worker on iOS Cache First works wonderfully with CSS and images, but falls apart with video and audio, and the cause lies in the requests themselves. In its Safari documentation, Apple requires a server hosting media files for iOS to support byte-range requests, because the player reads the file in chunks: it asks for a specific slice with the Range header and expects 206 Partial Content in reply. If the worker answers such a request with a fully cached file and a 200 status, the video on the iPhone may stall at the zeroth second or break on seeking. You can't cache a clip on the fly, either. During playback, partial 206 responses arrive from the network, and the Service Worker specification forbids putting them in the cache, so cache.put() with such a response rejects with a TypeError. If you really need offline video, it is downloaded in full ahead of time via cache.add(), and for requests with Range you cut out the needed slice yourself. Workbox has a workbox-range-requests module for this, and its documentation separately notes that <video> and <audio> tags need the crossorigin attribute even for files from your own origin. In the handler above, requests with Range bypass the worker and go straight to the network. For most apps that's the right choice: let the CDN serve long video. Offline Queue on iOS Without Background Sync A cache solves reading without a network; it doesn't solve writing: you can't send a POST /api/orders through caches.match(). Offline writing is built as a queue of domain operations ("create an order," "attach a photo," "cancel a request"), each with its own identifier, body, status, and creation time, and that queue lives in IndexedDB. You record the operation at the moment the person pressed the button, before any attempt to go to the network, and the interface tells the truth: "We'll send it when the network is back," with no green checkmark that later turns out to be a lie. The operation identifier works as an idempotency key: the server uses it to recognize a repeat and doesn't create a second order. The request might have reached the server while the response got lost in a subway tunnel, and on a resend with the same key the server must return the result of the first attempt instead of creating a second order. Without this, an offline queue will sooner or later start breeding duplicates, and support will be the one cleaning them up. On Chromium, such a queue is often entrusted to Background Sync, and the browser itself wakes the worker when the network returns, even if the app is closed. iOS has neither that nor Periodic Background Sync nor Background Fetch, so a phone in a pocket won't finish sending anything for you. The queue goes out when the app is back on screen: at launch, on returning from the background, and on the online event. Workbox adds no miracles here. In browsers without Background Sync, the workbox-background-sync module replays the queue on every worker startup, and its documentation says outright that this requires a page controlled by the worker to be running. On the iPhone, that's the same send-on-open, just hidden inside a library. JavaScript // app.js; db is a wrapper over IndexedDB (for example, idb) async function createOrder(payload) { const op = { key: crypto.randomUUID(), kind: 'create-order', payload, status: 'pending' }; await db.put('outbox', op); renderPending(op); flushOutbox(); } async function flushOutbox() { for (const op of await db.getAll('outbox')) { if (op.status !== 'pending') continue; const res = await fetch('/api/orders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': op.key }, body: JSON.stringify(op.payload), }).catch(() => null); if (!res) return; if (res.ok) await db.delete('outbox', op.key); else if (res.status < 500) await db.put('outbox', { ...op, status: 'failed' }); } } addEventListener('online', flushOutbox); addEventListener('pageshow', (e) => e.persisted && flushOutbox()); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') flushOutbox(); }); Such a queue usually breaks on 4xx responses. If the server rejected an order because of an outdated price, retries won't help, and the operation is marked as problematic so the person sees it with a "Fix" button. flushOutbox can also start simultaneously from online and visibilitychange; the key prevents duplicates, but a simple "already sending" flag will save the server some work. Page lifecycle events on the iPhone come with their own confusion. freeze and resume from the Page Lifecycle API exist only in Chromium, and Safari doesn't support them, so you have to rely on the long-standing visibilitychange (fully working in Safari since 14.1) and pagehide. Starting an IndexedDB write from scratch inside them is pointless, since the page may not have enough time, and that is exactly why the operation must reach the disk earlier, at the moment of the action. But pageshow with event.persisted equal to true is useful: the document was restored from the back-forward cache (bfcache), scripts didn't run again, the data on screen may be stale, and it's the right time to refresh it and send the queue. There's no need to register the worker again at that moment; it's already in place. IndexedDB Blocked by a Connection From Your Own Worker When a new version of the app raises the schema version (indexedDB.open('warehouse', 3)), all open connections to the old version receive a versionchange event. If even one doesn't close, the open request gets blocked, and upgradeneeded won't start while the connection is alive. On desktop the culprit is usually a second tab. An installed app on the iPhone shares a database with Safari no more than with the neighboring app, there is no second tab, and so it's all the more surprising to discover that the connection is held by your own worker: it opened the database to read the queue or the settings and never closed it. The cure is discipline on every connection, in the window and in the worker alike: db.onversionchange = () => db.close(), and in the worker, short-lived connections rather than one eternal one. In onblocked, it's better to show "Close the app and open it again" than to spin a spinner that will never stop. Web Push on iPhone Through APNs and the Home Screen Icon Web Push arrived on the iPhone and iPad in iOS and iPadOS 16.4 in March 2023, and only for web apps on the Home Screen. You can't subscribe in a Safari tab: the person first installs the app and opens it from the icon, and only then can you offer notifications. The offer should come in response to an explicit action such as tapping an "Enable notifications" button, and Apple's documentation advises calling the subscription directly from that tap's handler. After consent, a web app's notifications are configured in the system settings like any other app's, respect Focus modes, and reach Apple Watch. The subscription works the same way as in other browsers, only stricter. pushManager.subscribe() requires userVisibleOnly: true, and Safari enforces that promise: silent push without a notification isn't supported. WebKit writes that breaking the promise leads to the subscription being revoked, and Apple's documentation words it even more harshly: the notification permission is revoked. In the WWDC22 talk about the macOS Ventura beta, a threshold of three such pushes was mentioned; what it is now hasn't been stated publicly, and I wouldn't find out in production. The server identifies itself to the push service with VAPID keys. This is a key pair on the P-256 elliptic curve: the public one is passed to applicationServerKey at subscription time, and the server uses the private one to sign a short-lived JWT for the Authorization header. By RFC 8292, the aud field in the token contains the push service's origin, and exp may not be more than 24 hours after the moment of the request. Apple adds its own conditions: sub must be a URL or a mailto: address, and there's no need to refresh the token more than once an hour. The authors of the popular web-push library warn separately in the README that a sub with localhost gets bounced by Apple with a 403 BadJwtToken error, and over such a trifle it's easy to end up in a situation where notifications arrive on Android but not on the iPhone. The endpoint field in a Safari subscription points to a subdomain of push.apple.com (in real subscriptions that's usually web.push.apple.com), and delivery is handled by the same Apple Push Notification service (APNs) that native apps use. Membership in the Apple Developer Program isn't required. If your server's outbound traffic is restricted by an allowlist, open all of *.push.apple.com, as both WebKit and Apple advise, because nobody has officially promised a specific host. The payload in APNs is limited to 4 KB, which is exactly the minimum that RFC 8030 requires any push service to accept. APNs stores an undelivered message for as long as the TTL says, 30 days at most, and for a 410 response there is only one right reaction: delete the expired subscription from your database. JavaScript // app.js: subscribe only from a click handler const reg = await navigator.serviceWorker.ready; pushButton.addEventListener('click', async () => { const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: VAPID_PUBLIC_KEY, }); await fetch('/api/push/subscriptions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sub), }); }); // sw.js self.addEventListener('push', (event) => { const msg = event.data?.json() ?? {}; const n = msg.notification ?? { title: 'Update available', navigate: '/' }; event.waitUntil( self.registration.showNotification(n.title, { body: n.body, tag: n.tag, data: { url: n.navigate } }) ); }); self.addEventListener('notificationclick', (event) => { event.notification.close(); const url = new URL(event.notification.data?.url ?? '/', self.location.origin).href; event.waitUntil((async () => { const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); const existing = windows.find((w) => w.url === url); return existing ? existing.focus() : self.clients.openWindow(url); })()); }); In the push handler, the notification is shown first thing. The temptation to go to the server for details first is understandable, but on a slow network it easily turns into a push without a notification, with all the consequences discussed above. The fields in the message are called notification.title and notification.navigate for a reason: that is the Declarative Web Push format from the next section. And clients.openWindow() works only in response to a user action: per the specification, without user activation the promise rejects with InvalidAccessError, and a worker has essentially one such action, a click on a notification. You can't open a window from fetch or push. Before opening a new one, it makes sense to look for one that's already open via clients.matchAll() and focus it, so a click on the fifth notification doesn't spawn a fifth copy of the warehouse. I keep the address inside the app's scope, because the documentation doesn't describe iOS's behavior with a foreign address from openWindow. Declarative Web Push Without JavaScript In iOS and iPadOS 18.4 (March 2025), Declarative Web Push arrived for web apps on the Home Screen, and the WebKit post that introduced it is quite frank about why. Classic push rests entirely on JavaScript in a worker, and a bug in the script, a poor network, or a lack of time on the device easily ends in a push without a notification and a penalty for which the script's author isn't always to blame. On top of that, ITP deletes the data of long-unopened sites together with the worker registration, and the subscription is then left hanging in the air. In the declarative variant, the server describes the notification and the system displays it, without a single line of your code. You can subscribe straight from the window via window.pushManager, with no worker needed; if one is registered at the root scope, the subscription is shared between the window and the worker, and deleting the worker's registration doesn't cancel it. The message itself is JSON in the push body: JSON { "web_push": 8030, "notification": { "title": "Order 1842 is packed", "body": "The courier will pick it up by 2 PM", "navigate": "https://shop.example/orders/1842", "lang": "en-US", "dir": "ltr", "tag": "order-1842" } } The number 8030 refers to RFC 8030, which defines the push delivery protocol, and that's how the browser knows the message is declarative. Inside notification, title and navigate (the address that opens on tap) are required, and the remaining fields repeat the familiar notification options: body, lang, dir, tag, icon, silent, data, and actions buttons with their own navigate. In the example from the WebKit post, app_badge for the counter on the icon is there too, but the Push API specification draft has no such field yet, and I treat it as a WebKit-specific feature. The worker doesn't leave the game, though. If one is installed, it can receive a push event in which event.notification holds the proposed notification, and show its own instead, for example by decrypting the text with a key stored on the device itself. The spec draft sends this event only when the message has "mutable": true at the top level, while the WebKit post describes the behavior more loosely, so I'd verify the specific iOS version on a real phone. If the worker didn't make it in time or crashed, the system will show the original notification, and there's no penalty for a silent push here, because it can't be silent. This format coexists with older iOS versions without problems. On versions 16.4 through 18.3, and in browsers without support, the same message arrives as an ordinary push, and the handler from the previous section, which reads notification.title and notification.navigate, displays it itself. The server sends everyone one format: new devices manage without JavaScript, old ones cope as before. I would move the server to this JSON right now, even if most of your users are still on older versions. Debugging a Service Worker With Safari Web Inspector Debugging a worker from users' screenshots is useless; you need Web Inspector connected to a real phone. On the iPhone, it's turned on in Settings: the Safari section (in newer iOS versions it lives inside Apps), then Advanced and the Web Inspector toggle. On the Mac, in Safari's settings on the Advanced tab, you need to enable the features for web developers. The phone connects by cable, and once it agrees to trust that Mac, you can enable connecting over the network in the Develop menu and go on without the wire. The phone has its own submenu in the Develop menu, and in its lower part there are two sections that matter to us. Home Screen Web Apps shows the installed app while it's in the foreground, and it has nothing to do with a Safari tab at the same address: the tab has its own storage and its own set of workers. Service Workers shows the workers themselves, and Apple warns in its documentation that only a running one can be inspected. If the worker has fallen asleep, the section simply isn't there; open the app, do something that triggers a fetch, and go straight to the menu. The worker's inspector has its own console and breakpoints on the push, fetch, and notificationclick handlers. Safari has no Cache Storage viewer. The Storage tab has Cookies, Local Storage, Session Storage, and Indexed Databases, and that's it: the task of showing the Cache API contents there has been open in the WebKit tracker since May 2020 (bug 211335). You have to inspect caches from the console, where await caches.keys() shows the names, and (await (await caches.open(name)).keys()).map((r) => r.url) shows what's inside. You can unregister from the same place with (await navigator.serviceWorker.getRegistrations()).forEach((r) => r.unregister()), bearing in mind that unregister() takes effect after pages are closed and doesn't delete caches, which are cleaned separately. You can also start from a clean slate the blunt way: delete the icon and install the app again. When people complain that "offline doesn't work," I first answer four questions for myself and only then dig into strategies: does a worker control the page (navigator.serviceWorker.controller), does the address fall within its scope, is the needed request sitting in the right cache, and which worker controlled the page before the reload. A small thing helps with the last one. The worker broadcasts its version to clients in activate, the app displays it on a hidden About screen next to the build number, and a screenshot from support immediately answers half the questions. The Offline toggle in the inspector is good for checking fetch logic, but it doesn't reproduce process unloading, a cold start, or a full disk. Before a release, I walk through the scenarios by hand on a phone: a fresh install, an update over yesterday's version, airplane mode with the app swiped away from the switcher, signing out and signing in as someone else. I separately look at a screen for which nothing has ever been in the cache, because a good app tells "I'm showing the last saved version" apart from "this document isn't on the phone." And one more check that almost everybody skips: open the app after a day of idleness, when iOS unloaded it from memory long ago, and the worker comes up from scratch. That is exactly how an ordinary user will open it the morning after a release. If they see either the new version or a banner offering to update, and the unsent orders are in place, the worker is configured correctly. And if the shell from the cache arrives instantly but the interface still feels sluggish, the cause is no longer the worker or the network, but rendering and WebKit's main thread. That is exactly the question we'll take up in detail in the next article. Other Parts in This Series PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They LookPWA on iOS, Part 2: HTTPS, Manifest and Service WorkerPWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOSPWA on iOS, Part 4: What Add to Home Screen Really DoesPWA on iOS, Part 6: Performance, Rendering, and Keyboard More
Detecting Duplicates With Machine Learning in 2026: From String Metrics to Embeddings and LLMs

Detecting Duplicates With Machine Learning in 2026: From String Metrics to Embeddings and LLMs

By Ilya Dudkin DZone Core CORE
The more data companies gather on their customers, products, and code, the more duplicated information accumulates, confusing the teams who depend on it. You don't go through millions of records manually. So deduplication is now a machine learning problem. This article looks at the current state of duplicate detection in ML systems where the old techniques still work, and what embeddings and large language models have brought to the table. How Do ML Systems Detect Duplicates? It is possible for a person to look at two pictures or two strings and know if they are the same. Teaching a machine to do the same raises difficult questions. What is 'like'? There are degrees of resemblance. Is “Jon Smith, 12 Oak St.” the same customer as “Jonathan Smith, 12 Oak Street?” In practice, modern deduplication pipelines work like a funnel that begins with cheap, fast methods and introduces intelligence (and cost) only where necessary: Normalize block. Clean the data (case, punctuation, abbreviations, etc.) and group records into blocks where they share something in common (e.g., postal code or the first letters of a name). Only records within the same block are compared.Score candidate pairs using string metrics. Fast deterministic similarity measures catch typos, transpositions, and formatting differences.Embeddings for meaning. Dense vectors and approximate nearest neighbor search can discover pairs that are worded differently but mean the same.Push borderline cases up. If the earlier stages cannot be confidently settled, an LLM or a human reviewer resolves the pairs. Each stage decreases the number of pairs that the next, more expensive stage has to consider. This makes the approach affordable at scale. String Metrics Still Matter String metrics are the first line of defense. They are fast, interpretable, and do not need a model. Some common options are: Hamming distance: The number of positions at which two strings of equal length differ, or the number of substitutions needed to change one string into the other.Levenshtein distance: Generalizes Hamming to allow insertions and deletions as well as substitutions, so it works on strings of different lengths.Jaro-Winkler similarity: Measures the number of matched characters and transpositions, with more weight for a common prefix. It works particularly well with short strings, such as personal names.Sørensen–Dice coefficient: A measure of similarity based on the number of common bigrams (adjacent letter pairs).Jaccard similarity and TF-IDF cosine similarity: Comparing sets of tokens or weighted vectors of words; the latter is more suitable for longer text.MinHash with locality-sensitive hashing (LSH): a cheap way to estimate set similarity, so you can find near-duplicate documents without comparing them all.Learnable distance: understands that different domains have different weights for edit operations and learns those weights from labeled data. In a modern pipeline, these scores are typically features that go into a classifier, not the final answer. For example, a model can learn that a mismatch in a phone number is much more important than a mismatch in a middle initial. Vector Search and Embeddings String metrics break down when two texts say the same thing in different words. Take two questions from a Q&A site. How can I get cheap hotel rooms?What are the best ways to get cheap hotel deals? They have very few words in common, and thus have a rather high edit distance rating. Sentence-embedding models, by contrast, map each text into a vector space where similar texts are near each other. Then finding duplicates becomes a nearest-neighbor search: Python from sentence_transformers import SentenceTransformer import faiss questions = [ "How do I book cheap hotel rooms?", "What are the best ways to find cheap hotel deals?", "How do I renew my passport?", ] model = SentenceTransformer("all-MiniLM-L6-v2") vectors = model.encode(questions, normalize_embeddings=True) # Inner product on normalized vectors equals cosine similarity index = faiss.IndexFlatIP(vectors.shape[1]) index.add(vectors) scores, neighbors = index.search(vectors, k=2) for i, (row_scores, row_ids) in enumerate(zip(scores, neighbors)): for score, j in zip(row_scores, row_ids): if j != i and score > 0.7: # tune this threshold on labeled data print(f"Possible duplicate: {questions[i]!r} ~ {questions[j]!r} ({score:.2f})") The flat index above is fine for thousands of records. For millions, switch to an approximate index such as HNSW or IVF, which trades a little recall for large speedups. Before reaching for approximate search, check whether simple blocking already shrinks your comparison space enough. The similarity threshold is not universal. Tune it on a labeled sample of your own data, because the right cutoff for support tickets will differ from the right cutoff for customer names. LLMs for the Tough Cases Embeddings provide you with candidates, not certainty. Two product listings might differ only in a model number that matters, but otherwise be nearly the same vector. That’s where big language models are earning their place now, as a pair resolver that looks at two candidate records and decides whether they refer to the same real-world thing. Open-source tooling has started to package this pattern. One example is cocoindex, which uses FAISS embedding similarity to find near-duplicate entity names, and then queries an LLM-based resolver to confirm matches and choose the better canonical name. Academic work is moving in the same direction. A SIGMOD 2026 paper on in-context, clustering-based entity resolution with LLMs includes ways to reduce hallucinations and API calls. There are two caveats: Cost and delay. Send LLM calls only for the pairs the cheaper stages couldn't resolve, as LLM calls are much more expensive than string comparison. That’s why the funnel is there.Matches that have been hallucinated. An LLM can confidently speak of a wrong merge. Keep confidence scores, log reasoning, and have a human in the loop for high-stakes merges. Real World Examples Questions on Q&A Sites: Duplicates Sites such as Quora and Reddit are constantly bombarded with the same questions over and over again because users don't know someone else has already asked them. The most famous benchmark here is the Quora Question Pairs dataset, which came out in 2017 with about 404,000 labeled training pairs [check exact counts; the original paper reported 404,290 training pairs and 2,345,795 test pairs]. The benchmark is hard because duplicates are meaning-based, not word-based; capitalization, abbreviations, and context all matter. The above hotel example is a good first test for any approach. Embedding models do a much better job on this task than edit distance. Marketplace Duplicate Listings On classified-ad and marketplace sites, sellers will often re-post or slightly edit a listing if it's not performing. The same funnel applies: block by category and location, score titles and descriptions with string metrics, use embeddings to catch rewording, and flag the clusters for removal or consolidation. Another signal could be added for image similarity when listings have photos. Copy Code The biggest example of how much duplication builds up at scale is GitHub. Its Octoverse 2025 report says the platform now has 630 million total repositories, with 121 million added in 2025 alone, and 395 million of them are public or open source. It has more than 180 million developers. At that size, duplicated code is a must. Code duplication can be exact copies or clones that behave the same, but are written differently. Research on the topic (including a widely cited 2017 study of code duplication on GitHub, DéjàVu) found that a large share of JavaScript files were copies [verify the study’s details and the 93% figure before citing it, and make clear that this was academic research rather than something GitHub itself runs]. The newer story is AI-assisted coding. GitClear research of 211 million changed lines of code in 2025 found an eightfold increase in 2024 in code blocks that duplicate adjacent code with five or more lines. It also found for the first time that copy-pasted lines outnumbered moved (refactored) lines. GitClear sells code-review analytics, and its data shows correlation with AI adoption, not proof of cause, so treat it as vendor research. But it hints that code deduplication will grow in importance as AI tools make it easier to generate new code than to consolidate it. Duplicate Records in CRM Software Traditional CRM de-duplication relies on matching rules, and rules can’t cover all fuzzy cases. A learning-based approach, however, identifies fuzzy duplicates by combining multiple string metrics and learning from human feedback: the system shows you a pair of records, you mark them as duplicate or distinct, and it adjusts its matching accordingly. You can learn more about this in my previous article. The second big advantage is scalability. Comparing every record with every other record is quadratic. Now suppose you have 50,000 records and add 5,000 new records. Which means 50,000 x 5,000 = 250,000,000 comparisons to compare each new record with each existing record. That is almost 7 hours, 10,000 comparisons per second: 250 000 000 / 10000 / 3600 ≈ 6.94 hours If you compare every record with every other record in the combined 55,000 records, you get roughly 1.5 billion pairs or about 42 hours at the same speed. Blocking does this by grouping records with common characteristics and only comparing within each group, which reduces the amount of work to be done dramatically. Vector search does something similar, returning only the nearest neighbors of each record. AI Pipelines Duplicates Deduplication has also become a core step in the artificial intelligence systems themselves: Training data: Removing near-duplicate documents, often using MinHash and LSH, so models don't over-weight repeated text.RAG corpora: Collapsing repeated passages so retrieval doesn’t fill the context window with copies of the same content.Knowledge graphs: Marrying differently named entities like “Mr. Edwards,” “Brad Edwards,” and “Detective Edwards,” so relationships don’t break across duplicate nodes. Some tools now leverage a combination of deterministic rules, semantic similarity, LLM reasoning, and human review to do this.Pitfalls to plan for: False merges are worse than missed duplicates. Merging two different customers can corrupt the records and break downstream processes. Choose the more costly error and set the limits accordingly Just measure it. Evaluate on a labeled sample of pairs with precision, recall, and F1. Re-check as your data changes. Keep Humans in the Loop Low-confidence pairs are passed to reviewers, and their decisions are fed back into the system. A few considerations remain important: Data privacy: Records about people often contain sensitive information. Confirm what you send to hosted embedding or LLM services, and apply your organization's data-handling policies.Provenance: Keep original records and a merge log so that a bad merge can be undone. Machine learning will play an increasingly important role in deduplication, but it doesn't eliminate the need for human judgment. Any CRM, database, or codebase has a real price for duplicate data, and hand-written filters cannot handle the variety of ways duplicates show up. What the last few years have taught us in practice is not that one technique has replaced another. It’s that the best systems layer them: string metrics and blocking for speed, embeddings for meaning, and LLMs or people for the hardest calls. Start with the cheapest stage that works on your data, evaluate it, and only add the next stage if the results justify the cost. More
Building Enterprise Authentication With Angular, Spring Boot, SSO, and MFA
Building Enterprise Authentication With Angular, Spring Boot, SSO, and MFA
By Vaishnavi Khosla
Java to TypeScript in a Day: AI Migration Playbook
Java to TypeScript in a Day: AI Migration Playbook
By Anuj Kapoor
PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
By Konstantin Shkurko
Guess the Speed: Building a Family Internet Speed Guessing Game
Guess the Speed: Building a Family Internet Speed Guessing Game

In this blog post, we will see how I turned our family's speed test ritual into a family internet speed guessing game that you can play on your own Wi-Fi. Every family has that one argument. "The internet is slow again." "No, it is fine; you are just streaming in 4K." Nobody really knows who is right, because nobody knows the actual speed. So we started guessing before every speed test. It became a game, and the game became a website. Let's see how it works and how I built it. The author describes developing Guess the Speed, a multiplayer game that transforms family internet speed tests into a competitive activity. Players submit secret download and upload guesses before running a real speed test against Cloudflare's network, then earn points based on accuracy using place rankings, bonuses for close guesses, and a cutoff rule for large misses. The post details features including room codes for multiplayer phone participation, a TV-optimized display mode, live result gauges, and shareable results. It explains the technical implementation using Astro, TypeScript, Cloudflare Workers, and Durable Objects for managing game rooms, alongside privacy measures like automatic data deletion and cookieless analytics. The author reflects on lessons learned about focused game design, the appeal of real data, and privacy as a feature. Why I Built It Speed test night on the living-room TV became our family game night. Everyone shouts a guess before I press go. Here is the funny part. My kids get it right almost every time, and Dad loses on purpose. I started my career in performance testing, then moved into development, so I think I am allowed to be bad at guessing speeds. That is my excuse, anyway. At some point I realized this was a real game. It needed scores, secret guesses, and a proper winner. So I built it. How a Round Works A round takes about a minute. Here are the steps: Add players and pick a face for each one.Everyone locks in a secret download guess and a secret upload guess.Run a real speed test against Cloudflare's network.Compare the guesses with the result and score the closest players. That's it. No accounts, no sign-up, nothing to install. As shown below, the home screen keeps all of this on one page, with the live gauge in the middle and the player cards around it. A Sample Round (With Real Scoring) Let's ground this with one simple example. Say the speed test returns 240 Mbps download and 20 Mbps upload. Three players locked in their guesses: PlayerDownload guessUpload guessMom25022D&J20030Dad50050 Now the scoring rules kick in: Place points: first place earns 3 points, second earns 2, and third earns 1.Spot-on bonus: +1 point for each guess (download or upload) within 5% of the real value.50% cutoff: if your average miss is over 50%, you get no place points. Here is how our round shakes out: Mom is closest overall. Her download guess is only about 4% off, so she also gets the spot-on bonus. Total: 3 + 1 = 4 points.Mia lands second with 2 points.Dad guessed way too high. His average miss is far beyond 50%, so he gets 0 points. Dad loses on purpose, remember? In this round, the cutoff rule made sure he lost on merit too. The Features I am Most Happy With Once the basic game worked, I kept adding things that make it feel good in a real living room. Room codes for everyone's phones. Start a room, share a six-letter code or a QR code, and up to 12 players can join. Everyone guesses from their own phone. The server keeps all guesses private until the results are revealed, so nobody can peek and copy. The host also chooses which device runs the test. TV mode. This is a bigger gauge and bigger text, built for a couch ten feet from the screen. It supports fullscreen and uses a screen wake lock where the browser allows it, so the TV does not fall asleep mid-round. A live gauge with clear stages. You can follow the test through ping, download, and upload with live values and result cards. Watching the needle move is half the fun. Share the winner. The champion dialog shows the winner and the scores next to a Share result button. It uses the device share sheet or copies a link. Festive themes. Pick light, dark, or a seasonal theme, or leave it on Auto (by date) and let the calendar decide. Dev diagnostics. This one is for the curious. It shows the summary, latency samples, individual test requests, a bandwidth percentile, the test plan, and browser details. You can copy or download the latest run as JSON. Add ?dev=1 to the URL to open it. How It Is Built I kept the stack small and boring on purpose: Astro and TypeScript build the static site, which is served from Cloudflare Workers.@cloudflare/speedtest runs the real speed test in the browser.A GameRoom Durable Object manages the multiplayer rooms, using WebSocket hibernation so idle rooms cost almost nothing.A PlayStats Durable Object keeps the aggregate play counter.Game and scoring rules live in src/lib and are covered by Vitest tests. A few things I want to call out. Scoring is plain, testable code. Rules like the 50% cutoff and the tie-break are exactly the kind of thing that breaks quietly. Keeping them in src/lib with unit tests meant I could change the rules without fear. Durable Objects fit this problem well. One room is one object, and it holds the secret guesses until reveal. That is a natural fit for "a small piece of shared state that many phones talk to." Testing without waiting. Real speed tests take time, so I added a simulated mode. Append ?mock=1 for a short fake test. Use ?tv=1 to jump straight into the TV layout. To run it locally: Shell npm install npm run dev And to exercise rooms and the play counter, run the Worker locally: Shell npm run dev:worker Deployment is handled by Cloudflare Workers Builds. wrangler.jsonc runs npm run build, then npx wrangler deploy uploads dist as static assets. The Durable Object migrations run as part of that deploy. Everything below comes from the open-source repo at https://github.com/QAInsights/guessthespeed, so you can read the real code. Architecture at a Glance Astro and TypeScript build the static site, served by a Cloudflare Worker.worker/index.ts is the HTTP entry point. It creates rooms and upgrades WebSocket connections.GameRoom (worker/game-room.ts) is a Durable Object. There is one per room, and it owns the sockets and the stored state.src/lib/room.ts and src/lib/scoring.ts hold the rules as plain TypeScript functions with no Cloudflare APIs, covered by Vitest. The design rule I followed: the Durable Object is a thin shell. It loads state, calls a pure function, persists the result, and broadcasts. All the game decisions live elsewhere. One Durable Object Per Room A room code maps straight to an object with idFromName. Every phone that knows the code reaches the same instance, and every message for that room is handled in one place. That means there is no distributed locking to think about. Room codes are six letters from a 19-letter consonant alphabet, which gives roughly 47 million combinations. Creating a room means picking a code and asking its object to initialize itself. If the object already holds a room, it answers 409, and the Worker tries another code. TypeScript // worker/index.ts (simplified) for (let attempt = 0; attempt < 5; attempt += 1) { const code = generateRoomCode(/* crypto-backed random */); const hostToken = crypto.randomUUID(); const stub = env.ROOMS.get(env.ROOMS.idFromName(code)); const response = await stub.fetch("https://room.internal/init", { method: "POST", body: JSON.stringify({ code, hostToken, now: Date.now(), kind }), }); if (response.status === 201) return jsonResponse({ code, hostToken }, 201); if (response.status !== 409) return jsonResponse({ error: "room_creation_failed" }, 503); } return jsonResponse({ error: "room_code_unavailable" }, 503); The collision check needs no separate database. The object's own storage is the source of truth for whether a code is taken. The hostToken is a secret returned only to the creator. Presenting it on connect is what makes a socket the host. WebSockets That Survive Hibernation A room can sit idle for minutes while a family argues about the result, and I did not want to pay for an always-on object. The WebSocket Hibernation API lets the object be evicted from memory while the sockets stay connected. The catch is that anything held in memory is gone when it wakes up. Two things keep a room correct across hibernation: Game state lives in storage, not in fields. Each message handler starts with loadRoom().Per-socket identity lives in the socket attachment. After the first hello message, the object stores who this socket is with serializeAttachment. TypeScript // worker/game-room.ts (simplified) private async connectWebSocket(): Promise<Response> { if (!(await this.loadRoom())) return Response.json({ error: "room_not_found" }, { status: 404 }); if (!roomHasCapacity(this.ctx.getWebSockets().length)) return Response.json({ error: "room_full" }, { status: 503 }); const pair = new WebSocketPair(); this.ctx.acceptWebSocket(pair[1], ["room"]); return new Response(null, { status: 101, webSocket: pair[0] }); } private async handleHello(socket: WebSocket, message: Record<string, unknown>) { // ...validate clientId against a UUID pattern... const room = await this.loadRoom(); const attachment = { clientId: message.clientId, isHost: typeof message.hostToken === "string" && message.hostToken === room.hostToken, }; socket.serializeAttachment(attachment); this.sendState(socket, room, attachment); } The clientId is a random UUID the browser generates once and keeps in local storage. A returning phone sends the same ID, so the server can match it to its player after a dropped connection or a screen sleep. The reply to hello is always a full state snapshot, not a replay of missed events, so a reconnect cannot drift. One tradeoff worth naming: my per-socket rate limiter is an in-memory WeakMap, so it resets when the object hibernates. I treat the limits as a safety net, not accounting, so losing them on wake is acceptable. The Server Is the Referee Clients never change state directly. They send an action, and the server decides. TypeScript // worker/game-room.ts (simplified) const room = await this.loadRoom(); const result = applyAction( room, attachment.clientId, attachment.isHost, parsed, Date.now(), { onlineOwners }, ); if ("error" in result) { sendError(socket, result.error); this.sendState(socket, room, attachment); // resync the sender return; } await this.ctx.storage.put(ROOM_KEY, result.room); this.broadcastState(result.room); applyAction(room, clientId, isHost, action, now) returns either a new room or an error code. It takes now as a parameter instead of reading the clock, which makes it trivial to test. The room tests run actions in sequence and assert on the result, with no sockets involved. When an action is rejected, the sender gets the error plus the current state. That small habit fixed a whole class of stale-UI problems, because the client always snaps back to the truth. Keeping Guesses Secret If the server broadcast one shared state object, anyone could open dev tools and read everyone's guess. So the server never sends the raw room. It builds a view per recipient. TypeScript // src/lib/room.ts (simplified) const reveal = room.game.phase === "results" || room.game.phase === "champion"; players: room.game.players.map((roomPlayer) => { const { owner, ...player } = roomPlayer; delete player.guessedAt; return { ...player, guess: reveal || owner === clientId ? { ...player.guess } : { down: null, up: null }, mine: owner === clientId, }; }), TypeScript // worker/game-room.ts private broadcastState(room: Room): void { for (const socket of this.ctx.getWebSockets()) { const attachment = getAttachment(socket); if (attachment) this.sendState(socket, room, attachment); } } Each socket gets its own projection: your own guess, nulls for everyone else's, until the results phase. The same function strips internal fields like the owner and the guess timestamp. A room test asserts that other players' guesses stay hidden from both players and the host while guessing and testing, then appear at reveal. Cleaning Up Rooms With a Sliding Alarm Rooms should disappear after six hours of inactivity. My first version called setAlarm after every accepted action, which meant a storage write for every guess and every tap. A later commit replaced that with one rule: only schedule an alarm if none exists, and let the alarm re-arm itself. TypeScript // worker/alarm.ts export function alarmToSchedule( existingAlarm: number | null, deadline: number, ): number | null { return existingAlarm === null ? deadline : null; } TypeScript // worker/game-room.ts (simplified) async alarm(): Promise<void> { const room = await this.loadRoom(); if (room && Date.now() < room.updatedAt + ROOM_TTL_MS) { await this.ctx.storage.setAlarm(room.updatedAt + ROOM_TTL_MS); // still active return; } await this.ctx.storage.deleteAll(); for (const socket of this.ctx.getWebSockets()) { try { socket.close(1000, "Room ended"); } catch { continue; } } } The room stores updatedAt. When the alarm fires, it checks whether the room was active since it was scheduled. If yes, it sets a new alarm for the new deadline. If not, it deletes everything and closes the sockets. The result is a sliding time-to-live with at most one alarm in flight. Scoring as Pure Functions Scoring rules are exactly the kind of code that breaks quietly, so they live in src/lib/scoring.ts with no I/O. The core of it is a relative miss for each metric. TypeScript function metricMiss(guess: number | null, actual: number): number { if (!(actual > 0) || !Number.isFinite(actual)) return 1; return guess === null ? 1 : Math.abs(guess - actual) / actual; } // miss = (downMiss + upMiss) / 2 // bonus = Number(rounded(downMiss) <= spotOnPct) + Number(rounded(upMiss) <= spotOnPct) Looking back at our round: Mom's download miss is |250 - 240| / 240, about 4.2%, which is under the 5% spot-on limit. Her upload miss is 10%, so no second bonus. Place assignment skips players over the cutoff and handles ties the way a race does: tied players share a place, and the next place is skipped. JavaScript let place = 0; for (let index = 0; index < eligible.length; index += 1) { if (index === 0 || compare(eligible[index - 1], eligible[index]) !== 0) { place = index + 1; } eligible[index].place = place; eligible[index].placePoints = settings.placePoints[place - 1] ?? 0; } Two small details earned their own tests: Rounding before comparing. Misses are rounded to four decimals before ties are detected. Without that, floating-point noise decides who is tied.A zero or missing real speed. metricMiss returns a full miss instead of dividing by zero, so scores stay finite. The test file has cases for each rule: 3, 2, 1 points, an exactly 50% miss staying eligible, shared ties, the download-then-upload tiebreak, a player with no guess, and fewer than three players. TypeScript it("awards 3, 2, and 1 for first, second, and third", () => { const scores = scoreRound( [player("one", 100, 20), player("two", 90, 18), player("three", 70, 16)], actual, defaults, ); expect(scores.map(({ place, placePoints }) => [place, placePoints])).toEqual([ [1, 3], [2, 2], [3, 1], ]); }); Race Mode and the Server Clock Race mode changes the rule: the host starts the test, and players can guess while it runs. A guess locked in later earns a bigger share of the points, but a guess that misses the result earns nothing. The interesting design question is who owns the clock. Phone clocks drift and phones lag, so every timestamp comes from the Durable Object. Starting the test stores raceStartedAt: now, each guess stores guessedAt: now, and the result computes the timing bonus from the same server clock. TypeScript // src/lib/scoring.ts (simplified) const duration = endedAt - raceStartedAt; const fraction = duration === 0 ? 1 : Math.max(0, Math.min(1, (guessedAt - raceStartedAt) / duration)); const timingBonus = 0.5 + 0.5 * fraction; const total = Math.round(basePoints * timingBonus); The bonus ranges from 0.5 for a guess at the very start to 1.0 for a guess at the last moment. A table-driven test pins the edges and a rounding case. TypeScript it.each([ [0, 0.5, 25], [50, 0.75, 38], // 37.5 rounds up [100, 1, 50], ])("applies timing at %s%% of the test", (at, timingBonus, total) => { const [score] = applyRaceTiming( [baseScore], [{ id: "racer", guessedAt: at }], 0, 100, ); expect(score).toMatchObject({ basePoints: 50, timingBonus, total }); }); Applied to our round, with place points scaled to 30, 20, 10 in race mode: Mom's base is 30 plus a 10-point spot-on bonus, which is 40. If she locks in at 80% of the test, the bonus is 0.9, and she scores 36. Mia's base is 20, and locking in at 20% gives 0.6, so she scores 12. Waiting is rewarded, as long as you do not wait too long. There is one more leak to close. If players could watch the live speed climb, they would copy it in the last second. In race mode, the progress relay forwards only the step counters and drops the measurements. JavaScript const keys = race ? ["step", "steps"] : ["mbps", "pingMs", "step", "steps", "bytes"]; The relay also accepts progress only from the device assigned to run the test, and it is throttled to ten updates per second. Challenges and Lessons A few things that needed more than one attempt: Redundant alarm writes. Resetting the alarm on every action was correct but wasteful. The sliding alarm in section 7 fixed it.Host handover edge cases. Handing the host role to another phone sounds easy. The rules are: only the host can do it, not while a test is happening, not to an offline player, and not to the same device. The offline case shipped as a follow-up fix after a handover to a disconnected player left a room with no live host.Interrupted tests. If the device running the test reloads mid-test, the room can get stuck in the testing phase. A small pure function, interruptedTestStep, decides what the client does next: resend a result it already holds, or abort the round once.Abuse limits on a public endpoint. Messages are capped at 2 KB, each socket at 20 messages per second, rooms at 12 players, and WebSocket upgrades check the origin. Worker request bodies are size-bounded too.Testing real-time behavior without waiting. Because the rules are pure, most tests never open a socket. For the browser, a ?mock=1 flag runs a short fake speed test, so a full round takes seconds. What I would tell someone starting a similar project: Keep the Durable Object thin and move every decision into functions that take now as an argument.Never broadcast shared state when players should not see each other's data. Project a view per socket.Put the identity in the state in storage, and assume the object can wake up empty at any time.Prefer one self-rescheduling alarm over resetting a timer on every message. Privacy Decisions A game for families should not feel like a tracking machine, so I made a few choices early: In single-screen mode, settings, player names, and scores stay in your browser's local storage.Room names, faces, guesses, and scores are deleted after six hours without activity.The play counter stores totals only, and Cloudflare Web Analytics is cookieless.The speed test itself runs in your browser against Cloudflare's network. You can read the full details on the privacy page. Try It On Your Own Wi-Fi Here is how to play your first round: Head to https://guessthespeed.com/.Add everyone playing and pick a face for each person.Lock in your secret guesses (or have people join from their phones with the room code).Press go and watch the gauge.Check the scores and share the champion. If you want ideas for a full evening, there is a family game-night guide on the site. There is also a guide that explains how the real speed test works, and a 30-minute classroom activity for kids. What I Learned A few takeaways from this build: Small, focused games beat big ideas. The whole concept fits in one sentence, and that makes every decision easier.Real network data makes people care. A made-up number is boring. A real measurement on your own Wi-Fi starts arguments, which is exactly what a game needs.Privacy is a feature. Deleting rooms after six hours and keeping analytics cookieless cost me very little, and they make the game easier to recommend to other families. So that is Guess the Speed. A speed test, a few secret guesses, and a family that cannot stop arguing about the Wi-Fi. Which of your guesses would be furthest off: your download speed or your upload speed? Let me know in the comments below. Happy gaming!

By NaveenKumar Namachivayam DZone Core CORE
PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
PWA on iOS, Part 2: HTTPS, Manifest and Service Worker

This is Part 2 of the PWA on iOS series, and it’s the most practical one. There will be almost no history or corporate politics here, but there is groundwork you need for the rest of the series to make sense. You’ll learn why a PWA works on a laptop but not on an iPhone, and how HTTPS, the manifest, the Service Worker lifecycle, and two caches decide that. The typical story starts at a desk. The frontend runs on a laptop, the phone is on the same Wi-Fi network, Safari on the iPhone has an address like http://192.168.1.20:5173 open, and everything looks fine: the interface loads, the buttons work, and our PWA's icon sits next to the others on the phone's Home Screen. Then someone turns on airplane mode, taps the icon, and instead of the app, sees a message saying the page can't be opened. Meanwhile, everything is green in Chrome on the laptop: the worker is registered, the cache is full, and the team spends the first half hour hunting for a bug in the manifest, even though the phone has never seen that worker. No official tool will give you the answer, either. In iOS 26, Apple removed the last formal installation requirements, and any site added to the Home Screen now opens as a web app by default. The WebKit blog put it bluntly: "Put simply, Safari now has no requirements at all for installation." Google, for its part, stopped using Lighthouse as a PWA checker. Until Lighthouse 12, it had a separate PWA category: a set of automated checks that produced a score and showed whether an app met the criteria of an installable progressive web app. Lighthouse 12.0, released in April 2024, removed the PWA category, following Chrome's relaxation of its installability criteria. Even earlier, the Chrome blog acknowledged that the service worker check wasn't producing the intended result: sites were adding a worker with an empty fetch handler just to pass it. The green "this is a PWA" checkmark is gone on both platforms, and there is now only one way to tell whether you have an app or just a website with an icon: pick up a phone and test. Behind every web app icon on your phone's screen are three things: HTTPS, a service worker, and a manifest file. People usually think of HTTPS as the padlock in the address bar, but here it's needed for something else: without it, the browser simply won't agree to run code that acts as the bridge between the page and the network. The manifest is the simplest of the three: a small JSON file linked from <head> that records the app's name, start page, display mode, scope and icon. And the most interesting layer, the Service Worker, is a separate script the browser runs alongside the page but without access to its interface. The app's network requests pass through it, and it decides whether to go to the network, serve a saved copy, or show a fallback page when there's no connection. Why a Service Worker Needs HTTPS and a Secure Context A service worker is dangerous precisely because it's long-lived: once installed, it keeps running on later visits to the site and can intercept page requests within its scope. That's why registration is allowed only over HTTPS. The worker effectively sits between the web app, the browser, and the network, and it can alter requests and responses. If sw.js could be registered over plain HTTP, an attacker on public Wi-Fi could swap that file just once. A malicious worker would then stay in the user's browser and could keep serving altered HTML and JavaScript on later visits, harvest API data, or redirect requests to another server. Moving the site to HTTPS afterward wouldn't be an instant fix either: requests are handled first by the installed service worker, which can return a forged response from its cache or change how the network is accessed. The risk of this kind of attack is one of the reasons browsers require HTTPS for service workers. That's where the secure context requirement comes from. A page counts as secure if it was delivered over HTTPS or from an address the browser trusts on its own: localhost and its subdomains, the 127.0.0.0/8 range and ::1. Home or office network addresses like 192.168.x.x and 10.x.x.x aren't on that list. To the browser, that's plain HTTP, however much you trust your router. The sneakiest part is the way the browser says no. In the specification, navigator.serviceWorker is marked as available only in secure contexts, and on an HTTP page it simply isn't there. The check 'serviceWorker' in navigator, which almost every registration example starts with, quietly returns false, the code skips registration, and not a single error shows up in the console. That explains the story from the start of this article: on the phone, the worker didn't fail with an error. It never even tried to start. Let’s Encrypt and Free HTTPS Certificates for PWAs About ten years ago, many teams heard "use HTTPS" as "spend money and deal with hassle." You bought a certificate from a certificate authority and renewed it by hand, and for an internal tool or side project, that meant an extra line in the budget and an extra date on the calendar that everyone forgot until the morning the site started scaring visitors with a red warning. Let's Encrypt, a nonprofit certificate authority run by ISRG, changed that. On December 3, 2015, it entered public beta: invitations were no longer required, certificates were free, and the announcement stated the goal plainly: "We want HTTPS to be the default." Cost was only half of the problem. The server proves on its own that it controls the domain and obtains a certificate on its own via the ACME protocol, with no human involved and no correspondence with a certificate authority, and in March 2019 the IETF made that protocol official as RFC 8555. Let's Encrypt certificates are valid for 90 days by default, and such a short lifetime is practical only because there's no need to renew them by hand. These days, getting HTTPS for a worker takes about one toggle in a hosting panel, or a Certbot container next to nginx. I think this quietly ended many of the PWA arguments on internal projects: the money argument is gone, and what's left is the laziness argument. Testing a PWA on iPhone With HTTPS, Tunnels and mkcert On the laptop itself everything works, because http://localhost is on the trusted list and browsers on macOS will happily register a worker with no certificate at all. Trouble starts when you pick up the phone. On an iPhone, localhost means the iPhone itself. The laptop can only be reached by its network address, and to Safari that address is ordinary insecure HTTP. There are two workable paths: route traffic through a tunnel with a real certificate, or teach the phone to trust your own. The tunnel is easier. The command cloudflared tunnel --url http://localhost:5173 brings up what Cloudflare calls a quick tunnel. You get a random subdomain on trycloudflare.com, requests to it travel through Cloudflare's network to your local server, and the address has a public certificate, so the iPhone trusts it with no setup. ngrok http 5173 does the same through its own service. Cloudflare states plainly that quick tunnels are intended only for development and testing, and points to a different tunnel type for production. The tunnel has a catch that people only notice a week later. The random address changes on every launch, and a new subdomain means a new origin to the browser (the scheme, host, and port by which a browser tells one site from another). To an iPhone, every such address becomes a separate app: yesterday's icon points to a subdomain that no longer exists, today's starts with empty storage and no worker, and a row of identical icons for your PWA gradually grows on the test phone. If you plan to test an update on top of an old version, set up a permanent address: a named tunnel or your own domain. The second path goes through a local certificate authority, and the easiest way to set one up is with mkcert. The command mkcert -install creates a root certificate on your Mac and adds it to the system trust store, and mkcert 192.168.1.20 localhost issues a certificate for the dev server. The Mac is now happy. The phone isn't yet. You need to move the rootCA.pem file from the folder shown by mkcert -CAROOT to the iPhone via AirDrop, email, or a local web server, and install it as a profile. Then comes a step almost everyone skips: open Settings > General > About > Certificate Trust Settings and turn on your certificate under "Enable Full Trust for Root Certificates." Apple's instructions say explicitly that for profiles downloaded from a website or sent by email, trust for SSL/TLS has to be enabled manually, and without that switch the installed profile changes nothing. This setup has a price, and the mkcert README names it plainly: the rootCA-key.pem file gives full power to intercept secure requests from your machine, and it must never be shared. A root certificate on the phone works in the same direction. As long as it's trusted, whoever holds the key can issue a certificate for any domain, and the iPhone will accept it. I keep such profiles only on test devices and remove them when the test setup is no longer needed. Clicking through a certificate warning doesn't count as trust. A page with a self-signed certificate will open if you push through the warning screen, but registering a worker on it usually ends in an error, and until someone surfaces that error on screen, developers keep fixing the manifest. How to Register a Service Worker and Read Registration Errors Once you have HTTPS, registration itself looks modest, and almost everything interesting in it happens in the catch branch: JavaScript // app.js if ('serviceWorker' in navigator) { window.addEventListener('load', async () => { try { const reg = await navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none', }); console.info('[sw] scope:', reg.scope); } catch (error) { console.error('[sw] registration failed:', error); } }); } else { console.warn('[sw] navigator.serviceWorker is missing: HTTP or an old browser'); } The else branch handles that silent refusal on HTTP: better one warning line in the console than half an hour of guessing. I hook registration to load so that downloading and installing the worker doesn't compete with the first render for the network, which is noticeable on slow mobile connections. The scope parameter sets the scope, meaning the prefix of addresses whose requests the worker will intercept. By default it equals the directory where the script itself lives. A worker at /assets/sw.js can't take control of / unless the server sends a Service-Worker-Allowed: / header along with the script, so it's simpler to keep sw.js in the root. We'll come back to updateViaCache in the section on caches; it has a surprising wrinkle. Don't leave the catch branch empty or skip it. Its errors usually tell a specific story that you won't see on a laptop. The specification forbids redirects when loading a worker script, so an sw.js that the server redirects to the www version of the domain, to a CDN or to a login page won't register at all. If the server serves the script with the wrong MIME type (the content type from the Content-Type header), registration fails with a SecurityError. This happens most often in SPAs, single-page apps where JavaScript handles all navigation and the server answers any unknown path with index.html: instead of a script, the browser gets HTML. One more small thing helps with debugging. The browser adds a Service-Worker: script header to the request for a worker script, so such requests are easy to find in logs or to single out with a separate rule on a CDN, the network of caching servers in front of your backend. Installing is up to the user. iOS has no beforeinstallprompt event and no way to trigger the system install dialog from code. The person opens the Share menu and picks Add to Home Screen, and in iOS 26 sees a toggle there, "Open as Web App," which is on by default. What happens in the system at that moment, where the icon and splash screen come from and what MDM has to do with it, we'll cover in Part 4 of this series. Web App Manifest Fields Safari Supports on iOS The manifest is hooked up with one line in <head>: <link rel="manifest" href="/https/dzone.com/manifest.webmanifest">. The file can have any name, and manifest.json works too, because the browser follows the link and doesn't look for a file by name. The right response type is application/manifest+json. It's registered with IANA together with the .webmanifest extension, and the specification recommends serving the manifest with it. Plain application/json is accepted in practice as well, but I'd go with the first so the next person on the team doesn't have to guess what's behind that address. Safari 15.4 brought a small but welcome change: the browser now downloads the manifest along with the page, whereas before it did so only at the moment the user added the site to the Home Screen. The manifest request is now visible in Web Inspector right away, and you don't have to install the app every time just to check. Here's the file for our imaginary app: JSON { "id": "/", "name": "Field Journal", "short_name": "Journal", "start_url": "/?source=home-screen", "scope": "/", "display": "standalone", "theme_color": "#0d1b2a", "background_color": "#f4f7f9", "icons": [ { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" } ] } Going by MDN's compatibility tables, Safari on iOS reads noticeably less from this file than Chrome does. It has understood name, short_name, start_url, scope and display since iOS 11.3, the very beginning of manifest support. theme_color arrived in iOS 15, icons in 15.4, and id in 16.4. Icons come with a condition described in the Safari 15.4 release notes: Safari takes them from the manifest only if the HTML has no apple-touch-icon and the icon either has no purpose or has any. WebKit added the id field in the same release as Web Push, so that notifications and badges would work for several installs of the same app, for example a work copy and a personal copy with different accounts. According to MDN, the iPhone ignores most of the rest. orientation, description and share_target aren't supported on iOS, and Safari understands shortcuts only on macOS, starting with version 17.4. Of the display values, standalone and browser work on iPhone, while fullscreen and minimal-ui aren't supported. The exception is background_color: Safari uses it, together with name, when creating the web app's launch screen. You don't need to remove the other fields from a shared manifest. They're useful on Android and Chrome, and they don't bother Safari. But don't count on them for anything critical on iPhone. short_name is the label under the icon, and it's meant to survive the cramped Home Screen: "Field Journal" might not fit there, "Journal" will. start_url doesn't have to point to the site root. A parameter like ?source=home-screen is handy for analytics, so the server can see launches from the icon, but don't use it to check authorization, because anyone can type such an address. Relative paths inside the manifest are resolved against the manifest's own address, and a start_url from a different origin must, per the specification, be ignored, with the current page's address used instead. id comes with a trap that's easy to miss. If the field is missing, the app's identity per the specification is start_url, and a harmless tweak of an analytics parameter can look to the browser like the appearance of a different app. I set id explicitly in the first release and never touch it afterward. "id": "/" is resolved against the origin and becomes the site root, a stable name that survives any experiments with the start page. display: "standalone" asks for a separate window without an address bar, and theme_color sets the color of the system elements around the page. Both fields are requests to the browser and have nothing to do with your interface's CSS. The browser will carry them out in its own way. Why Apple Meta Tags Still Matter in 2026 Apple taught the iPhone to open sites without browser chrome long before the W3C took up the manifest, and it did so with its own meta tags. They haven't gone anywhere, and I still keep both sets in <head>: HTML <link rel="manifest" href="/https/dzone.com/manifest.webmanifest"> <meta name="theme-color" content="#0d1b2a" media="(prefers-color-scheme: dark)"> <meta name="theme-color" content="#f4f7f9" media="(prefers-color-scheme: light)"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <link rel="apple-touch-icon" href="/https/dzone.com/icons/apple-touch-icon-180.png"> apple-mobile-web-app-capable historically asked iOS to launch the site from the icon without Safari's interface. In iOS 26 that became the default behavior for any site, but duplicating it is still useful if some of your users are on older iOS versions or on corporate devices that are rarely updated. apple-mobile-web-app-status-bar-style controls the status bar, the one with the clock and battery, and Apple's old reference describes three values for it. With default and black, the page starts below the status bar, while with black-translucent it takes the whole screen and the status bar partly overlaps it. It looks great right up until the first header slides under the clock, so check your insets with env(safe-area-inset-top) as soon as you use that value. The most useful thing in this bunch, I think, is apple-touch-icon. Since Safari 15.4, it explicitly takes priority over manifest icons, and WebKit explains this as a wish to preserve the behavior of sites that have a separate icon drawn for iOS. Use an opaque 180×180 PNG: a transparent background was historically handled badly on iOS, and on older versions the alpha channel turned into a black backing. If the tag isn't there at all, iOS, according to Apple's documentation, looks for files with the apple-touch-icon prefix in the site root on its own. That's where the endless 404s for /apple-touch-icon.png in your server logs come from, the ones nobody can usually explain. Safari won't use an icon whose only purpose in the manifest is "maskable", since that value comes from Android's icon conventions. theme-color arrived in Safari 15 and turned out to be more noticeable than expected. In Safari on iOS 15 it colors the status bar and the area visible when you scroll past the edge of the page, and with a media attribute you can set different colors for light and dark themes, as in the example above. After that the story gets murkier: MDN's tables note that as of Safari 26, the theme-color color is used only in installed web apps. I didn't find that wording in Apple's release notes, so check on whichever iOS version you have in hand, and don't promise your designer a colored header in a Safari tab. Service Worker Lifecycle and skipWaiting on iPhone The most persistent misconception about workers is that a worker runs in the background all the time, like a daemon on a server. The browser starts it for an event (a page request, a push notification, a message from a tab) and may stop it right after the event is handled. A worker has no DOM and no window, and global variables live only until the next stop, so a "sync in progress" flag stored in a variable will be empty after the worker wakes up. Anything that has to survive the worker being stopped should be written to Cache Storage or IndexedDB. A service worker's lifecycle is designed so that a new version doesn't break pages that are already open. After register(), the browser downloads the script and compares it byte for byte with the installed one, and if there's no difference, that's the end of it. A new script gets an install event, in which it usually puts the app shell into the cache, meaning the HTML, styles and scripts without which the interface can't be drawn. Then it waits in the waiting state while the old version serves open tabs, and only when none are left does it get activate, clean up old caches and start receiving fetch events from pages in its scope. On the first run there's one more confusing detail: the page that registered the worker isn't controlled by it until the next navigation, unless the worker calls clients.claim(). JavaScript // sw.js const VERSION = 'shell-v7'; const SHELL = ['/', '/assets/app.8d91.js', '/assets/app.3c2e.css']; self.addEventListener('install', (event) => { event.waitUntil(caches.open(VERSION).then((cache) => cache.addAll(SHELL))); }); self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keys) => Promise.all(keys.filter((key) => key !== VERSION).map((key) => caches.delete(key))) ) ); }); self.addEventListener('message', (event) => { if (event.data?.type === 'skip-waiting') self.skipWaiting(); }); event.waitUntil() looks like a housekeeping detail, but without it the browser doesn't know the event is still in progress and is free to stop the worker before the cache is written. On the iPhone, where background processes inevitably get put to sleep, that's a very practical risk. cache.addAll() has a quirk of its own: it's atomic, and if even one file in the list returns a 404, the whole installation fails. The new worker then simply doesn't start, users stay on the old version, and your logs are empty, because the error happened on the phone. I don't write the list of app shell files (everything the app can't launch without) by hand. The build tool generates it from the real files with hashes in their names, so it can't contain an address that doesn't exist on the server. Optional images I cache in a separate step, so that one unavailable file can't fail the installation. The waiting state is often mistaken for a bug, though it's protection against shooting yourself in the foot. If a new worker takes over a tab where old JavaScript is already running, you get a mix of the old interface with the new cache or a new API contract. Calling self.skipWaiting() on every install, together with clients.claim() in activate, removes the waiting state entirely, and for a static site or strictly backward-compatible releases that's a fine choice. For an app with an IndexedDB migration or a changing offline data format, I don't do that, and in the code above the worker skips waiting only on a message from the page. The page, noticing registration.waiting, shows a "New version available" banner, sends reg.waiting.postMessage({ type: 'skip-waiting' }) on tap, and reloads in the controllerchange event handler. In my experience, on iOS this scheme noticeably reduces the number of mysterious bug reports from people who come back to the app after a couple of days in the background. Background work on the iPhone is more modest than tutorials promise. Background Sync, Periodic Background Sync and Background Fetch aren't available in Safari or other browsers on iOS. So a photo upload queue that will "send the files by itself ten minutes from now, while the phone sits in your pocket" won't work. A Service Worker wakes up only when the app is open or when an event arrives that iOS is willing to deliver, such as a push. Send what has accumulated when the app returns to the foreground, and show the user that an operation is waiting for a connection. We'll cover updates, push, and IndexedDB storage in detail in Part 5 of this series. For now, remember this: a worker wakes up briefly and remembers nothing between wake-ups. Service Worker Cache Strategies and Opaque Responses In the fetch handler, the worker decides the fate of every request, and the most common mistake here is answering everything from the cache because that's what the tutorial did. For a hashed /assets/app.8d91.js, the Cache First strategy is nearly perfect: a file with that name will never change, and it doesn't need the network. For GET /api/orders, the same strategy will show yesterday's order as today's, and the user won't even know. In practice, there are three strategies, and each negotiates freshness with the user in its own way. The simplest, Cache First, returns the copy and goes to the network only on a miss. It belongs on versioned files, fonts, and icons. For HTML documents and data where freshness matters more than milliseconds, I use Network First: network first, and the saved response only when the network is down. The third strategy, Stale-While-Revalidate, is trickier. The user immediately gets the saved copy while the worker requests a fresh version in the meantime and puts it in the cache for next time. The response arrives quickly but may lag by one visit. For avatars, configs and feeds, that's usually fine. In the fetch handler, the strategy is chosen by what kind of data it is: JavaScript self.addEventListener('fetch', (event) => { const { request } = event; const url = new URL(request.url); if (request.method !== 'GET' || url.origin !== self.location.origin) return; if (request.mode === 'navigate') { event.respondWith(networkFirst(request, '/')); } else if (url.pathname.startsWith('/assets/')) { event.respondWith(cacheFirst(request)); } else if (url.pathname.startsWith('/api/feed')) { event.respondWith(staleWhileRevalidate(event)); } }); async function cacheFirst(request) { return (await caches.match(request)) ?? fetch(request); } async function networkFirst(request, fallbackUrl) { const cache = await caches.open(VERSION); try { const response = await fetch(request); if (response.ok) cache.put(request, response.clone()); return response; } catch { return (await cache.match(request)) ?? caches.match(fallbackUrl); } } async function staleWhileRevalidate(event) { const cache = await caches.open(VERSION); const cached = await cache.match(event.request); const fresh = fetch(event.request).then((response) => { if (response.ok) cache.put(event.request, response.clone()); return response; }); event.waitUntil(fresh.catch(() => {})); return cached ?? fresh; } Requests for which the worker didn't call respondWith() go to the network as usual, and I consider that the right default: anything you haven't explicitly classified should behave as if there were no worker. For the same reason, the first line filters out other hosts and everything except GET. For a third-party CDN without CORS, the browser gives the worker what's called an opaque response. Its status is 0, the body and headers are unavailable to the script, and response.ok is false. Code that checks ok won't cache it, and images that "seemed to be cached" will vanish when you're offline. You can put such a response in with put(), but then you won't know whether you've just saved a 404 for a month. Caching third-party resources makes sense only if the CDN sends Access-Control-Allow-Origin and the request goes in cors mode. Otherwise it's easier to proxy the files through your own domain or accept that they load only online. In staleWhileRevalidate, note event.waitUntil(). Without it, the cached response goes to the page, the browser decides the work is done, and it may stop the worker before the fresh version lands in the cache. Tutorials often skip that line, though on iPhone it's exactly what separates a real staleWhileRevalidate from an imitation. I handle page navigations separately, by request.mode === 'navigate'. A SPA opens addresses like /orders/42 that aren't in the cache as files, and if the offline fallback covers only /index.html, opening such a link directly without a connection ends in an error. For a SPA it's reasonable to return the cached shell /, as in the code above, and let the app decide which data to show. A server-rendered site can't do this: if you answer every address with the same shell, the worker will break link previews, diagnostics and SEO, and the team will then blame Safari. There, the fallback should be a separate page like /offline.html. credentials is a trap that can go unnoticed for a long time. fetch(event.request) inherits the settings of the original request, while a new Request assembled by hand sends cookies only to its own origin by default. As long as the API lives on the same domain, there's no difference. When the API moves to api.example.com while the app stays on app.example.com, requests rebuilt in the worker suddenly arrive without cookies, the user looks logged out only on the screens that passed through the worker, and reproducing it on desktop doesn't always work the first time. Responses with personal data are better kept out of the Cache API unless you've thought through sign-out. The cache is tied to the origin and knows nothing about the session, so on sign-out, delete the entries holding the user's data, and don't put responses that depend on a cookie or token into a shared cache out of habit. POST can't be put there at all, since the Cache API accepts only GET, and offline writes have to be built as a queue of operations in IndexedDB with an idempotency key and an explicit sync status. While the worker starts after a long idle period, navigation waits for it, and on iPhone that's sometimes visible as an extra empty frame. Since Safari 15.4 there's Navigation Preload: the browser starts the network request for the page in parallel with starting the worker, and in the handler you pick up the ready response from event.preloadResponse. It's enabled by calling self.registration.navigationPreload.enable() in activate, and it makes sense when documents already go through Network First. HTTP Cache vs. Cache API and How sw.js Updates There are actually two caches in the browser, and they know nothing about each other. The first, the HTTP cache, is always there. The browser itself stores server responses in it and decides on its own when they've gone stale, going by the Cache-Control, ETag and Vary headers. You control it only indirectly, through those headers. It can even answer a fetch() from a worker without waiting for the network, and it can evict an entry when it needs space. You can't rely on it offline. The second, the Cache API, exists specifically for the worker. It's storage that you manage by hand: what to put in, under which key, when to delete it, and what to return instead of the network. That's why offline is built on it: the files needed for launch sit where you yourself put them. The Cache API doesn't read headers. Even if the server allowed a file to be cached for a year via max-age=31536000, it won't get into the Cache API on its own, because only your code puts things there. And conversely, an entry in the Cache API won't be updated via ETag until you write that check yourself. The classic cache problem looks like this. A bundle is named /app.js with no hash, the worker put it in the Cache API at install, you shipped a fix, and caches.match('/app.js') keeps returning the old version: the key is the same, after all. The fix is simple: give the file a hashed name, such as /assets/app.8f3a.js, plus the header Cache-Control: public, max-age=31536000, immutable. Then you won't have to ask users to "clear the cache." Nobody deletes the old URL; people just stop requesting it. Hashed names have a flip side, and it hits SPAs especially hard. After a deploy, old files disappear from the server, while the user still has the previous version's shell open, and that shell asks for /assets/app.8d91.js. If the server answers any unknown path with index.html and a 200 status, the browser gets HTML instead of a script, fails while parsing it, and the user sees a white screen. Worse, a strategy that caches responses with a 200 status will save that HTML under the name of a JavaScript file. So I keep old assets on the server for at least one release and don't let the SPA fallback into /assets/: a missing file there must return 404, and nothing else. On nginx you can set it up like this: JavaScript location = /sw.js { add_header Cache-Control "no-cache"; } location = /manifest.webmanifest { types { } default_type application/manifest+json; add_header Cache-Control "no-cache"; } location /assets/ { add_header Cache-Control "public, max-age=31536000, immutable"; try_files $uri =404; } location / { try_files $uri $uri/ /index.html; } sw.js itself isn't part of the hashing scheme. It needs no-cache so that every check reaches the server, including through CDNs and proxies. This is where the promised detail about updateViaCache comes in. Per the specification, the default is 'imports', and with it the worker's main script is requested bypassing the HTTP cache during an update check anyway, while only files pulled in with importScripts() go through the cache. The value 'none' extends the same rule to imports, and 'all' brings the HTTP cache back for everything. According to MDN, Safari has supported this setting since version 11.1. I set 'none' in projects where several teams touch the cache infrastructure: it does no harm, and it insures against a single forgotten importScripts with a long max-age. The specification describes quite strictly when a browser checks for an update. A check is triggered on navigation to a page within the worker's scope, on functional events such as push if more than a day has passed since the last check, and on a manual call to registration.update(). If the last check was more than 86,400 seconds ago, the request for the script bypasses the HTTP cache in any case, even with updateViaCache: 'all'. For a SPA there's a trap hidden here: transitions through history.pushState don't count as navigation, and an app that's been open on an iPhone since morning may never ask the server about a new sw.js until evening. A "Check for updates" button in settings that calls update() and offers a restart when a waiting worker appears helps more than hoping for the daily timer. The browser will dutifully go to the network, but between it and the server there may be a CDN that someone once told to cache everything with a .js extension for a week. Then half of the iPhones sit for a week on a worker that no longer exists on the server, so check the rule for sw.js on the CDN separately, preferably with a request from a phone. Service Worker Scope Mistakes Including the Trailing Slash The specification compares scope as a string prefix, with no understanding of directories. A worker or manifest with a scope of /app will also capture /app-v2 and /application, and a new storefront will suddenly live on the old dashboard's cache. Write /app/ with a trailing slash, and after registering, look at registration.scope in the console. If it isn't the prefix you expected, you can stop debugging cache strategies. One origin can have several registrations with different scopes, and each page is controlled by the one whose scope matches its address and is longer than the others. That sounds convenient until the landing page has registered a worker on /, the dashboard has its own on /app/, and both start answering shared resources in their own ways. I've seen a test environment where, after such a story, the dashboard behaved differently depending on which page the person first landed on, and sorting it out took longer than writing both workers. It's calmer when an origin has one owner: one worker with routing inside fetch, or separate subdomains if the teams really can't share a file. A subdomain means a different origin, different cookies and a different cache, so it's a real boundary, not a free optimization. There's an API mix-up related to this. navigator.serviceWorker.getRegistration() takes a page address (scope has nothing to do with it) and returns the registration that controls that address, and without an argument it uses the current page's address. If you're looking for the dashboard's registration from the home page, pass an address inside the dashboard. Otherwise you'll get the landing page's registration and wonder for a long time why it has no waiting. Then there's the habit of registering sw.js?v=3 to "reset the cache." Jake Archibald, in an article on the worker lifecycle, explains where that ends up: the HTML of the page, which carries the new address, is itself sitting in the old worker's cache, and the user simply won't see the new address. His wording is worth quoting: "You've put yourself in a position where you need to update the service worker in order to update the service worker." Keep one permanent address, /sw.js, and leave freshness to the headers and to the byte-by-byte comparison that the browser does without you. The manifest's scope has its own mix-up, and it's often explained wrongly. Per the specification, if scope isn't specified, it's computed from start_url: the start address is taken without the file name, query and fragment, and the directory where the manifest lies plays no role here. The manifest can sit in the site root, but with "start_url": "/warehouse/index.html" and no scope, it gets a scope of /warehouse/, and a link to /account takes the person beyond the app's boundary. There the page, per the specification, stops being considered part of the app and is shown with browser elements again. If start_url doesn't lie inside an explicitly specified scope, the browser silently discards that scope and falls back to the default, so a typo in one field changes the boundaries of the whole app with no warning. The way out is simple: an explicit "scope": "/" where the account should be part of the app, or a conscious decision that it lives separately. The second, in my observation, almost nobody chooses. One last pitfall: manifest.webmanifest and sw.js must not hide behind authorization. If the server redirects an unauthenticated request to a login page, the worker won't register, because redirects are forbidden. The manifest case is funnier: Safari gets the login page's HTML in its place, and the icon on the Home Screen may well end up named "Sign In." Both files are public and contain no personal data, so serve them as static files, bypassing the app's router. In the Network tab this takes five seconds to check. If a text/html document arrived in place of the manifest, the installed app will take its name from the page's <title>. First Launch From the Home Screen Icon on iPhone The first visit happens entirely in a Safari tab. The page arrives over HTTPS, Safari downloads the manifest along with it, the script registers the worker, and the worker puts the shell in the cache and activates according to your policy. Then the person adds the site to the Home Screen, and here many expect the app to take along everything the worker managed to store. It won't. A web app on the Home Screen has its own storage, separate from Safari's, with its own cookies, localStorage, IndexedDB, and Cache Storage, so someone who has just signed in within a tab will see the login screen again in the app. On first launch from the icon, the worker registers again, now inside the app, and if there's no connection at that moment, there's nothing to show. That’s the second cause of the broken first launch from the story at the start of the article: even with correct HTTPS, the first launch of an installed app has to happen online. On the second launch, the icon opens start_url, and the already-active worker intercepts requests within its scope. If the network is gone, a well-thought-out strategy returns the shell and clearly shows that the data is offline and how fresh it is. If someone put index.html in the cache a year ago under Cache First and forgot about it, the user gets an interface that looks like it works and is hopelessly out of date, and an honest "data is unavailable right now" page would have been better than that surprise. Storage is also subject to a quota on the user's phone. The popular rule "iOS wipes everything for a PWA after seven days of non-use" wrongly stretches to installed apps a restriction that WebKit introduced in 2020 for site storage in Safari. In the same post, WebKit wrote that web apps on the Home Screen have their own days-of-use counter and that, under normal use, their data shouldn't be deleted. The system can still evict data when space runs short, so sync critical data to the server, show queue status, and test a cold start after a long idle period. How to Test a PWA on a Real iPhone Test on a real device, and test the installed app specifically: a Safari tab and the icon on the Home Screen use different storage, so success in one tells you nothing about the other. I run the same scenario every time: install on a clean phone, open from the icon with the network on, turn on airplane mode, fully close the app (swipe it up in the app switcher), and open it again. Then do the same thing on top of an old version to see how the new worker comes up, and separately, sign out, after which no one else's data should remain in the cache. One successful page reload on a laptop proves absolutely nothing. For debugging on an iPhone, there's Web Inspector. On the phone, it's turned on in Safari's settings, under the advanced options, after which the device connects to the Mac with a cable and its pages appear in Safari's Develop menu on the Mac. The console, network, and storage are all there, but debugging workers is, in places, less pleasant than in Chrome DevTools. I don't rely on the inspector alone, and I log what I'll need later to analyze a bug report: the worker version, the result of cleaning up old caches, and the cases when the offline fallback kicked in. A line like console.info('[sw]', VERSION, 'activate') and the shell version number somewhere on a settings screen save hours of back-and-forth with a user who has no idea which version they have. There's one scenario where none of the above helps. A link to your app sent in a messenger will open not in the installed web app, and not necessarily in Safari, but in the messenger's built-in browser. It has its own storage and its own restrictions, so the cache you've built is unavailable there. Why the same address behaves differently on iPhone in Safari, in a built-in browser, and on the Home Screen, and what WebKit has to do with it, we'll cover in Part 3 of this series. Other Parts in This Series PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They LookPWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOSPWA on iOS, Part 4: What Add to Home Screen Really DoesPWA on iOS, Part 5: Service Worker Updates, Cache, and PushPWA on iOS, Part 6: Performance, Rendering, and Keyboard

By Konstantin Shkurko
PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look

This is the first of eight articles about how web apps work on iOS, and it has less code than the rest. Here I look at where the oddities come from, the ones everyone who ships a PWA to the iPhone ends up living with. Open the <head> of almost any PWA built in 2026 and next to the manifest link you'll most likely find the apple-mobile-web-app-capable meta tag. Safari's old reference says it plainly: "Available in iOS 2.1 and later." Version 2.1 came out on September 12, 2008, when the App Store had already been running for two months. So full-screen web apps on the iPhone showed up after Apple had turned to the native SDK, even though the story is usually told the other way round. PWA behavior on the iPhone is full of small details like this. Behind the icon on your Home Screen are twenty-five years of attempts to turn a web page into a program, and plenty of the decisions made along the way are still sitting in your code. When Windows Trusted HTML as It Trusted Itself In 1999, together with Internet Explorer 5, Microsoft released HTML Applications, or HTA. For its time, the idea was very clear: HTML, CSS, and scripts can already draw an interface, so why not launch such a page in its own window like an ordinary Windows program, with no address bar and no browser buttons? A file with the .hta extension was opened by a system utility, mshta.exe, which took the IE engine but left its security model outside the door. Microsoft wrote about this in its documentation without a trace of embarrassment. HTAs are called "full-fledged applications" that "are trusted," and the summary reads: "an HTA runs like any executable (.exe) file written in C++ or Visual Basic." The user was asked once, before the download, whether to save the file or run it. After that, the app could do everything an ordinary program can: write to disk, start processes, read the registry. It looked roughly like this: HTML <html> <head> <title>Inventory</title> <hta:application applicationname="Inventory" border="thin" showintaskbar="yes" /> <script language="JScript"> function openLog() { var shell = new ActiveXObject("WScript.Shell"); shell.Run("notepad.exe C:\\inventory\\log.txt"); } </script> </head> <body> <button onclick="openLog()">Open log</button> </body> </html> No permission dialog, no origin, no sandbox: the WScript.Shell object runs anything with the current user's rights. For an internal admin tool in the late nineties that was convenient, sysadmins wrote setup wizards, support dashboards, and utilities in HTA that otherwise would have had to be built in Visual Basic. All of it ran only on Windows and only on the IE engine, so HTA couldn't boast the cross-platform reach that people usually pick the web for. Microsoft even patented the approach: the application "Method and apparatus for writing a Windows application in HTML" was filed on May 20, 1999, and patent US 6,662,341 was granted on December 9, 2003. Why .hta Is Still Stripped from Email Attachments The model of "download some markup, get the rights of a program" aged very badly. In MITRE ATT&CK, mshta.exe has a technique of its own, T1218.005, which describes how attackers run malicious .hta files, JavaScript and VBScript through the utility as early as the initial-access stage. A trusted system binary is handy because it slips past policies that only watch for unfamiliar executables. The LOLBAS project, which catalogs legitimate Windows programs that can be abused in attacks, lists mshta.exe with paths in System32 and SysWOW64 all the way up to Windows 11. The loudest episode happened in April 2017. FireEye described attacks through RTF documents for Microsoft Office: inside sat an OLE object with a link; Word went to the attacker's server on opening, got an HTA from there, and handed it to a handler that executed the file. The vulnerability was assigned CVE-2017-0199, and Microsoft fixed it in the update of April 11, 2017. In November 2021, CISA added it to its catalog of vulnerabilities exploited in real attacks. HTA itself wasn't the bug in that chain. It was just the full trust the attackers were after. Today Outlook blocks .hta attachments by default, on the same list as .exe and .bat, and I can't think of a better epitaph for the technology. What do PWAs have to do with it? Well, they look like apps, open from an icon and work offline, but they stay inside the browser security model, with its origins, HTTPS, sandbox, and permissions the user grants one at a time. When, in the next parts, a Service Worker refuses to register over plain HTTP, or iOS won't let a web app near Safari's data, remember mshta.exe: that's exactly the kind of neighbor browsers don't want to see next door anymore. June 2007: No SDK Needed On January 9, 2007, at Macworld, Steve Jobs showed the iPhone and said nothing about third-party apps. Today that looks odd, but back then the phone was sold as a finished product with mail, a browser, maps and an iPod inside, and the question of a platform simply never came up on stage. Developers got their answer on June 11 at WWDC. According to a transcript that 9to5Mac published later, Jobs said the iPhone has "the full Safari engine" inside, so you can write Web 2.0 and Ajax apps that "look exactly and behave exactly like apps on the iPhone," and then added: "There's no SDK that you need!" Apple's press release from the same day says the same thing in a calmer voice. Web apps would look and behave like built-in ones, and they could make a call, send an email, and drop a pin in Google Maps. They would extend what the iPhone can do "without compromising its reliability or security." And they could be updated by "simply changing the code on the developers' own servers." It sounds almost like a definition of a PWA, but in June 2007 there wasn't much behind those words. The app lived in a Safari tab, you reached it through a link or from your bookmarks, and all the integration with the phone came down to tel: and mailto: links plus addresses that opened in Maps. There was no camera API, no background work, and no storage in today's sense. There was no Home Screen icon at all: the Home Screen itself was fixed, and without a jailbreak you couldn't rearrange anything on it. Developers took to this model anyway, and with real enthusiasm. At iPhoneDevCamp in July 2007, Wired reported, the person everybody was talking about was Joe Hewitt, one of the creators of Firefox and Firebug. He had put together iUI, a set of templates that made a site on the iPhone look and act almost like a built-in app. Many developers had already adopted the templates as a base, and Wired wrote that they were clearly becoming the default look of the iPhone web. That August, Hewitt, by then at Facebook, built a version of the social network specifically for the iPhone, and it was a web app too: the native client didn't come out until the summer of 2008. To me, this model still feels more honest than the way it was later retold. The web didn't pretend to be deeply integrated with the phone. It asked the system to perform a system action, and that habit survived all the way to Web Share, and to the way an installed web app on iOS now asks for permission to send notifications. An Icon in January, an SDK in March The button this whole series exists for arrived with iPhone OS 1.1.3 on January 15, 2008. TidBITS described the novelty in detail at the time: Safari got a plus button, its menu had an Add to Home Screen item, and an icon appeared on the Home Screen that Apple called a Web Clip. The same release let you edit the Home Screen for the first time, icons started to wiggle under your finger, and the number of screens went up to nine. Apple's documentation has said the same thing ever since: "The Web Clip feature is available in iOS 1.1.3 and later." The apple-touch-icon was born along with the icon. A site could drop a PNG in the root or point to one in a <link>, and if it did neither, iOS went looking in the root for a file called apple-touch-icon.png. Later versions also tried variants like apple-touch-icon-57x57-precomposed.png. The -precomposed suffix, which has worked since iOS 2.0, was simply a request: Safari, please don't add your own effects to this icon. The era of glossy highlights is long gone, yet I still see requests for these files in server logs, on servers where nobody ever put them. Still, an icon added this way opened an ordinary Safari tab with all the toolbars. The first Web Clip was a bookmark moved to the Home Screen, and nothing more. Apple, meanwhile, had already changed its mind. Back on October 17, 2007, a short letter from Jobs appeared on the company's site. It began with the words "Let me just say it: We want native third-party applications on the iPhone" and promised an SDK in developers' hands in February. He blamed the delay on security: Apple was trying to give developers an open platform and protect users from viruses and malware at the same time, and he pointed to Nokia, which on some of its new phones allowed only apps carrying a digital signature from a known developer. Four months passed between the June "no SDK needed" and this letter. The SDK missed February. It was shown on March 6, 2008, together with the App Store, and the press release from that day contains a phrase that set the course for the next fifteen years: third-party apps "must be approved by Apple and will be available exclusively through the App Store." The store itself opened on July 10, 2008, through iTunes, and by the time the iPhone 3G went on sale, Apple was promising more than 500 native apps in it. iPhone OS 2.0, with the App Store built in, came out the next day, July 11. Full-Screen Mode Came After the App Store Now the detail I started with. The apple-mobile-web-app-capable meta tag hides Safari's interface and opens a site from its icon in full screen. Its neighbor, apple-mobile-web-app-status-bar-style, controls the strip with the clock. Apple marked both as available since iOS 2.1, and that version came out on September 12, 2008. The same reference describes the navigator.standalone property, which lets a page tell that it was launched from the Home Screen. The apple-touch-startup-image splash picture was added only in iPhone OS 3.0, and icons for different screen resolutions in 4.2. So Apple was still finishing the web app mode when the native platform was already on sale. There is no "first they bet on the web, then dropped it" in this timeline. Web apps got modest, minimal support and lived on it for almost ten years. What iOS kept from that period is a set you can still find in old projects: a separate meta tag for every capability, no general description of the app, and installation only by hand, through the Safari menu. A lot of projects have dragged the launch-mode check along since those days, and it usually looks like this: JavaScript const standalone = window.navigator.standalone === true || window.matchMedia('(display-mode: standalone)').matches; if (standalone) { document.documentElement.classList.add('launched-from-home'); } The first half of the condition is a legacy of iPhone OS 2.1, and the second arrived with the web manifest. On the iPhone, this check usually fails not because of the code but because of expectations: navigator.standalone exists only in WebKit on iOS, while the value of display-mode depends on exactly how the site was added to the Home Screen and what was in the manifest at install time. We'll break down how this works in Part 4 of this series. Ten Years on Meta Tags and AppCache Between 2008 and 2018, web apps on the iPhone stood on two things: those same Apple tags and the Application Cache. The tags were simple and tedious. For the splash screen, you had to draw a separate image for almost every iPhone and iPad screen size, in the right orientation and with the right media query. I've come across repositories where the folder of splash images weighed more than the app itself, with a comment sitting next to it along the lines of "don't delete, white screen on iPad otherwise." Offline was worse, and its roots, by the way, aren't Apple's. On May 31, 2007, less than two weeks before WWDC, Google released Gears, a browser plugin that gave pages a local SQLite database, background workers, and a LocalServer module that could serve saved HTML, scripts, and images without a network. Gears was what powered offline access in Gmail. On February 19, 2010, the Gears team wrote on its blog that its effort was shifting toward getting all of Gears' capabilities into web standards like HTML5, and that the plugin itself would get no new features. For the history of PWAs this is a telling moment: a browser vendor retired its own proprietary technology in favor of a standard, and Service Worker would later travel roughly the same road. The standard heir to LocalServer was AppCache. You declared a text file listing your resources in <html manifest="...">, and the browser promised to open the page without a network. Safari on the iPhone supported it, and for web apps launched from the Home Screen it was for a long time the only standard way to open without a connection instead of showing a "You are not connected to the Internet" error page. A typical manifest looked harmless: HTML CACHE MANIFEST # v12 CACHE: /index.html /app.js /styles.css NETWORK: /api/ FALLBACK: / /offline.html The catch was in the update rules. Apple's documentation warned outright that changing the HTML file does nothing until the manifest itself changes, so everybody kept a comment with a version number in it and remembered to bump it. If the manifest did change, the new cache was built in the background and applied only on the next visit, which meant the user saw the old version first and the new one only after a restart. If a single file from the list came back with an error, the update wasn't applied at all. Some users could get stuck on an old bundle for a long time without even knowing it. In May 2012, Jake Archibald, who was then building Lanyrd's mobile site on AppCache, published an article in A List Apart with a famously rude title: "Application Cache is a Douchebag." He went through all of these traps, and if I put it in my own words, AppCache looked like an offline mode but behaved like a hidden deploy that you don't control. Funnily enough, Archibald later ended up among the editors of the Service Worker specification, along with Alex Russell, who comes up below. Service Worker grew straight out of that grievance. Instead of a declarative list, you got a programmable fetch handler, an explicit lifecycle, and a Cache API where you decide for yourself what to store and when. If a legacy project still has <html manifest="cache.appcache"> sitting in it, don't try to migrate gradually by adding a worker alongside. Two offline mechanisms on one origin fight over the same page, and the bug then looks like "some users have the old version" even though git is perfectly clean. Remove AppCache, ship the worker, and check a cold start on a real device. How Apple Campaigned for HTML5 On April 29, 2010, Apple published Jobs's open letter "Thoughts on Flash," explaining why Flash wouldn't be coming to the iPhone, iPod and iPad. Most of the text is about battery life, stability, and the touch interface, but the most interesting part is how it talks about the web. "Rather than use Flash, Apple has adopted HTML5, CSS and JavaScript," Jobs writes, meaning open standards that its devices support quickly and efficiently. The letter ends with a forecast: "New open standards created in the mobile era, such as HTML5, will win on mobile devices (and PCs too)." There's also a line that's hard to read today with a straight face. Adobe, according to Jobs, claimed that Apple's decision was driven by business and a wish to protect the App Store, "but in reality it is based on technology issues." On Flash, I think, he turned out to be right in the end. But the forecast of HTML5's victory came from a company whose Home Screen web apps couldn't send notifications and relied on that very AppCache for offline. Safari was one of the best mobile browsers at the time, and WebKit inside it really did push standards forward, while the app mode stayed roughly where it had been left in 2008. Developers saw the contradiction. In November 2009, that same Joe Hewitt, by then the author, by TechCrunch's estimate, of the most popular iPhone app ever, handed the native Facebook client over to another engineer. He told the publication that the decision was entirely about Apple's policies and that he was fundamentally opposed to the review process. His explanation ended like this: "The web is still unrestricted and free, and so I am returning to my roots as a web developer." I think this contrast explains a whole decade better than any conspiracy theory. Apple was happy to promote the web as a technology for pages and much more careful about the web as an app platform on its own phone. At least that's how it looks from the outside, since the company doesn't publish its motives for each missing API. The most popular explanation for the pause comes down to the App Store commission. You can't prove that kind of causality from public sources, and I wouldn't build technical decisions on it. The engineering explanation is duller, but it can be checked: background execution, persistent storage, and notifications for websites sit badly with a phone's battery, memory, and permission model, and WebKit on iOS has to keep compatibility for years with everything it has already shipped. The commercial incentives don't go away because of that. They just don't explain why, for example, cache.addAll fails entirely because of one broken URL. Who Else Tried to Turn the Web into a Platform? Apple wasn't the only one in those years to look at HTML as a language for apps, and almost all of these attempts ended badly. They're worth remembering, if only so you don't repeat old arguments in PWA debates. Palm showed the Pre smartphone at CES in January 2009, and on June 6 it went on sale through Sprint. The webOS operating system was daring by design: the interface was built on WebKit, and third-party apps were written in HTML, CSS, and JavaScript with the Mojo framework. The Verge, in a long piece on Palm's history, quoted one of its sources explaining the choice: instead of keeping a person around whose job is writing code to center text, you can "stand on the shoulders of giants and let WebKit do it." According to the same piece, Palm ported the V8 engine for speed and was the first to ship it on a mobile device. The rest of the story is short. In 2010, HP bought Palm; on August 18, 2011, it announced it would stop making webOS devices, and in February 2013 it sold the system to LG, where it still lives on in TVs. Google came at it from a different side. The Chrome Web Store opened on December 7, 2010, and besides extensions, it distributed Chrome Apps, packaged and hosted apps that ran in Chrome almost like desktop programs. On August 19, 2016, the Chromium blog published "From Chrome Apps to the Web": packaged apps on Windows, Mac, and Linux were actively used by about 1% of users. Google announced that it would remove them from those platforms and told developers to move to Progressive Web Apps with Service Workers and Web Push. By mid-December 2017, Chrome Apps had vanished from search and the Chrome Web Store directory, although installed apps on those systems kept launching for a while. The final shutdown dates were pushed back several times after that, but the direction never changed again. Mozilla went further than anyone and built a whole operating system in which an app is a web page. The first commercial Firefox OS phone, the ZTE Open, went on sale through Telefónica in Spain on July 2, 2013, for about 90 dollars, aimed at emerging markets. On December 8, 2015, Mozilla announced it was ending development and sales of Firefox OS smartphones, and gave a fairly honest reason: "we weren't able to offer the best user experience possible." In the same statement, Mozilla wrote, not without pride, that Firefox OS had proved the flexibility of the web on devices ranging from cheap smartphones to HD TVs. In September 2016, commercial development stopped altogether, but the code didn't disappear. A fork grew into KaiOS, which ran feature phones such as India's JioPhone. Microsoft, in Windows 8, which went on sale on October 26, 2012, made HTML5 and JavaScript first-class languages for Windows Store apps, right alongside C# and C++. For that, there was the WinJS library, which was open-sourced under the Apache license in April 2014. The last commit to its GitHub repository is dated May 2020. Of the four, webOS survived most visibly, and even that moved into TVs, while Firefox OS carried on in someone else's fork for feature phones. Put these stories together, and the conclusion is an unpleasant one for people who love grand plans. The web as an app language lost every time it needed its own operating system, its own store, or an ecosystem it had to build from scratch. PWAs survived because they ask for none of that and ride inside a browser the user already has. That is exactly what makes iOS a special case. The browser on the iPhone belongs to the same company as the platform with the store, and every browser there has to run on WebKit (apart from regulated exceptions in the EU), so the pace at which PWAs gain new capabilities is set by Apple. WebKit and the DMA get a full treatment in Part 3 of this series. A Name for Something That Already Existed On June 15, 2015, Alex Russell of the Chrome team published "Progressive Web Apps: Escaping Tabs Without Losing Our Soul." He writes that the evening before, over dinner, he and the designer Frances Berriman had listed the properties of a new class of apps: they adapt to any screen, work offline thanks to Service Worker, are always fresh, are served only over TLS, can be found by search engines, can be put on the home screen, and open through an ordinary link. Berriman called them Progressive Open Web Apps. In the body of the post, they shrink to Progressive Apps, while the headline carries the combination that ended up sticking. My favorite line from it says that such apps aren't packaged or distributed through stores because "they're just websites that took all the right vitamins." The same post has a detail worth reading twice if you care about iOS. Russell describes a scenario using the Chrome Dev Summit site: at first it's an ordinary tab, and on the second, third, or fourth visit, once the browser is confident the site is used regularly, it shows an install prompt on its own, filled in with data from the manifest. Safari still has no such prompt, and that's exactly why so many PWAs for the iPhone have a homemade hint somewhere in the interface, with an arrow pointing at the Share button. The word "progressive" comes from the term progressive enhancement. A basic site works in any browser, and wherever Service Workers, a manifest, and push are available, offline support, an icon, and notifications get layered on top. Installation stays optional. If your app shows a blank screen without JavaScript and counts as broken without a registered Service Worker, you've built the exact opposite of what the authors of the term had in mind. That will show up first on an old corporate iPad sitting behind a temperamental proxy. The first big examples appeared quickly, and nearly all of them were about Android. On November 10, 2015, Flipkart engineer Aditya Punjani described how Flipkart Lite was built, the mobile site of India's largest online store: a single-page React app, HTML shells served from the Service Worker cache, offline browsing of recently viewed products, and notifications through Web Push. On April 6, 2017, Twitter announced Twitter Lite at mobile.twitter.com and promised it would take up less than a megabyte on the device. The same announcement has a caveat that deserves a careful read: notifications and offline worked "in Google Chrome and other modern browsers on Android devices." On the iPhone in 2017, both of them were just a fast website, because Service Worker didn't exist in Safari yet. Cupertino, We Have a Problem! iOS 11.3 came out on March 29, 2018, and Apple's press release about it talks about new ARKit features, Animoji, health records in the Health app, and the battery health screen. Not a word about Service Workers. It turned up in the release notes for Safari 11.1, which shipped with that iOS version: support for Service Workers with debugging in Web Inspector, the Cache API, the Web App Manifest for sites added through Add to Home Screen, and Payment Request for paying with Apple Pay. The WebKit overview separately notes that Service Workers are partitioned by the origin of the top-level document, so they can't be used to track a user across sites, and the implementation details are described in the post "Workers at Your Service." The word "support" has to be read very narrowly here. Maximiliano Firtman, who had already written a piece during the beta under the headline "Cupertino, we have a problem," listed right after the release what had been left out. There was no install prompt, so the user had to open the Share menu themselves and find the Add to Home Screen item. There were no push notifications. iOS ignored the icons from the manifest and took apple-touch-icon, and without one it built an icon from a screenshot of the page. There was no splash screen, most of the colors from the manifest were dropped too, and when you left the app its state wasn't preserved: you stepped out to check an SMS code, came back, and the PWA started from scratch. Even Uber's careful PWA threw the user out into Safari at the login step, after which nothing was left of the app mode but the name. Apple's decision makes engineering sense to me. The company switched on the standards it knew how to support inside its own process and under its own battery limits, and it didn't copy Chrome's behavior on Android. For people who had already shipped a PWA on Android and expected identical behavior on both platforms, it looked like mockery, and I can see why they felt that way. What Came Later After that, the story moved in fits and starts. Push for web apps added to the Home Screen arrived only in iOS and iPadOS 16.4, in March 2023, and WebKit's announcement immediately spelled out the conditions: notifications are available only after installation, and permission is requested in response to a user action. The same release brought the Badging API and the ability to add sites to the Home Screen from third-party browsers. Declarative Web Push, which no longer needs an installed Service Worker to show a notification, was added in iOS 18.4 in March 2025. In iOS 26, a site added to the Home Screen opens as a web app by default, and a toggle called "Open as Web App" controls that. I'll say more about storage, because that's where the most outdated advice has piled up. The figure of 50 MB came from write-ups in 2018 and stopped describing reality long ago. The "seven-day rule" appeared in March 2020, when Intelligent Tracking Prevention in Safari started wiping script-writable storage for sites the user hadn't interacted with in seven days of browser use. In the same post, WebKit clarified that web apps on the Home Screen have their own counter of days of use, and their own data shouldn't be deleted in normal operation. The system can still evict it if the device runs out of space, and Apple doesn't name a single public quota figure that covers every case. I draw one practical conclusion from all this. The server stays the source of truth, local storage is a cache that may vanish one day, and a cold start after such a wipe needs to be tested on a real phone. Five years between Service Worker and push meant one simple thing for a product: if your app needed notifications, until spring 2023 native was your only option on the iPhone, however good the PWA turned out. Why an Engineer Needs All This in 2026 The history is here because it's useful for the job. It helps you avoid mistaking an incompatibility for a bug in your own app, and the typical case goes like this: a team writes a correct manifest, checks it in Chrome DevTools, and on the iPhone sees an old icon or a screenshot in its place. Someone who knows only the manifest spec starts hunting for a mistake in the JSON. Someone who remembers the Web Clip looks first at apple-touch-icon, at the way the app was installed, and at the fact that the icon was saved on the device at the moment it was added and most likely won't update by itself. The minimal <head> that I put even into internal admin tools grows out of that same past: HTML <link rel="manifest" href="/https/dzone.com/manifest.webmanifest"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> <link rel="apple-touch-icon" href="/https/dzone.com/icons/apple-touch-icon.png"> On recent iOS versions, the apple-mobile-web-app-capable tag simply repeats display: standalone from the manifest, but on a line of tablets that go years without updates, that duplicate is cheaper than working out why the app opened in a tab. Make the icon an opaque 180×180 PNG in a separate file: the system isn't obliged to use a tab favicon for the Home Screen. Another benefit is that it pays to break the word PWA into parts before you even size up the task. On the iPhone, it hides three separate capabilities, and they arrived in different years. The icon and launching without a browser UI came in 2008 along with the meta tags; solid offline support became possible in 2018 with Service Workers, and notifications showed up in 2023, only for installed apps. An internal CRM often gets by with the first. A warehouse app needs the second, plus a queue of operations: iOS still has no Background Sync, so data will only go to the server the next time the app is opened. A messenger needs the third, and this is exactly where the web on the iPhone faces its tightest limits. This is also where the habit of naming a minimum iOS version comes from. "We support iOS" isn't a requirement: iOS 15, 16.4 and 18.4 are very different from one another. In 15, web apps have no push at all; 16.4 brought standard Web Push, and 18.4 added Declarative Web Push on top. Besides, in corporate environments old iPads stay in service much longer than the product team assumes. So I check not a list of APIs but scenarios on a real device: API names say little about how things actually behave in practice. The app should install with the right name and icon and open without the browser bar. After a full close, it should launch with no network; after sign-out, it shouldn't leave the previous user's data in the cache; and it should ask for notification permission only after installation and on a button tap. Lighthouse can do what it's good at, but it won't walk through the Web Clip install path for you (Apple calls that Home Screen icon a Web Clip). Another source of confusion comes from the 2016-2018 Android articles with their beforeinstallprompt, install banners and Google Play packaging. There is no such event on the iPhone, so a snippet that triggers a "native install dialog" is useless for Safari. I'd keep recipes like that in a wiki marked "Chromium only". Otherwise, sooner or later someone will carry them into the shared bundle and spend a week figuring out why the event doesn't fire on the iPhone, when it isn't supposed to. In requirements, instead of "make a PWA," I write three lines: the minimum iOS version, whether push is needed, and what has to work offline. If "sync in the background" shows up in the last line, it's better to end the "a PWA will do" conversation before anyone estimates in story points. And if everything adds up, the actual engineering begins. In Part 2 of this series, we'll put together a minimal setup of HTTPS, a manifest, and a Service Worker, and look at why updating without App Store review works in both directions: you can ship a broken sw.js in a minute, and in that same minute break the app for all your users at once. Other Parts in This Series PWA on iOS, Part 2: HTTPS, Manifest and Service WorkerPWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOSPWA on iOS, Part 4: What Add to Home Screen Really DoesPWA on iOS, Part 5: Service Worker Updates, Cache, and PushPWA on iOS, Part 6: Performance, Rendering, and Keyboard

By Konstantin Shkurko
Builder Pattern + Faker in API Test Automation Using Playwright With TypeScript
Builder Pattern + Faker in API Test Automation Using Playwright With TypeScript

Ever felt stuck writing Playwright tests because of messy or hardcoded test data? It usually starts simple, but as your tests grow, like testing an e-commerce or finance-related application, managing realistic data quickly becomes confusing and repetitive. More time is spent fixing test data than actually testing. That’s where the Builder Pattern, combined with Faker, can really help. It lets us create clean, flexible, and realistic test data with ease. In this article, we’ll learn how this approach can make the API tests with Playwright TypeScript easier to write, read, and maintain. What Is the Builder Design Pattern? The Builder Design Pattern is a creational design pattern that allows constructing complex objects step by step, allowing different representations of the same object. It separates object-creation logic from structure, making the code more readable and maintainable. This pattern is especially useful for objects with many optional parameters, as it avoids messy constructors and improves test data creation. What Is Faker? Faker is a library that generates realistic-looking fake data such as names, emails, addresses, numbers, and more. It is commonly used in testing to avoid hardcoding values and to simulate real-world data scenarios. By combining the Builder Pattern with Faker, we can generate realistic test data on the fly and perform testing without worrying about test data management, duplication, or maintenance. Faker can be installed using npm by running the following command in the terminal: Plain Text npm install @faker-js/faker --save-dev After installation, we can use the Faker library directly in the code by using the following import: TypeScript import {faker} from '@faker-js/faker'; How to Use the Builder Pattern With Faker in Playwright With TypeScript To use the Builder design pattern with Faker in Playwright TypeScript, the setup usually includes two main parts: ModelBuilder class The Model defines how the data should look, while the Builder class handles creating and customizing that data using Faker. Application Under Test We’ll use the POST /addOrder API of the RESTful e-commerce demo application for the demonstration. The following is the request payload of the API: JSON [ { "user_id": "string", "product_id": "string", "product_name": "string", "product_amount": 0, "qty": 0, "tax_amt": 0, "total_amt": 0 } ] Creating a Model for the Order The following model interface should be created for the Order payload: TypeScript export interface Order { user_id: string, product_id: string, product_name: string, product_amount: number, qty: number, tax_amt: number, total_amt: number } Code Walkthrough The Order interface represents the structure of an order object, where each field in the interface specifies the expected property and its data type: user_id, product_id, and product_name are strings.product_amount, qty, tax_amt, and total_amt are numbers. This interface ensures that any order object created in the code follows this exact structure, helping catch errors early and making the code more predictable and easier to maintain. Creating the Builder Class The following builder class is created to generate a new order with realistic fake values using the Faker library. TypeScript import { Order } from "../models/order.model.js"; import {faker} from '@faker-js/faker'; export class OrderBuilder { private order:Order; constructor() { const product_amount = faker.number.int({ min: 1, max: 100 }); const qty = faker.number.int({ min: 1, max: 5 }); const tax_amt = faker.number.int({ min: 2, max: 10 }); this.order = { user_id: this.generateUserId(), product_id: this.generateProductId(), product_name: faker.commerce.productName(), product_amount, qty, tax_amt, total_amt: (product_amount*qty)+tax_amt } } private generateUserId():string { return faker.number.int({min: 1, max: 50}).toString(); } private generateProductId():string { return faker.number.int({ min: 1, max: 100 }).toString(); } withUserID(user_id:string) { this.order.user_id = String(user_id); return this; } withProductId(product_id:string) { this.order.product_id=String(product_id); return this; } withProductName(product_name:string) { this.order.product_name = String(product_name); return this; } withProductAmount(product_amount:number) { this.order.product_amount= Number(product_amount); return this; } withQty(qty:number) { this.order.qty=Number(qty); return this; } withTaxAmt(tax_amt:number){ this.order.tax_amt=Number(tax_amt); return this; } withTotalAmt(total_amt:number) { this.order.total_amt= Number(total_amt); return this; } build():Order{ return this.order; } } Code Walkthrough The OrderBuilder class implements the Builder Pattern to create an Order object using Faker. The following is a detailed explanation of the code: Constructor(): The OrderBuilder class internally holds an Order object, which is based on the Order interface. In the constructor, it generates default random data using the Faker library.Private functions: The private functions, namely, generateUserId() and generateProductId(), are helper methods that generate random user IDs and product IDs, respectively.with() functions: The withX() functions, such as withUserId(), withProductId(), etc., allow overriding specific fields. Each method updates a value and “returns this,” enabling method chaining.Build functions: The build() function method finally returns the fully constructed Order object. In short, this class generates realistic test data by default while allowing selective customization, resulting in cleaner and more reusable test code. Writing the API Automation Test Using Playwright The following Playwright test demonstrates how to send a POST request using an order request payload generated through the Builder Pattern with the Faker library. TypeScript import { test, expect } from "@playwright/test"; import { OrderBuilder } from "../builders/order.builder.js"; import { Order } from "../models/order.model.js"; test("Add Order details using Builder Design Pattern", async ({ request }) => { const orderDetails = new OrderBuilder().build(); const orders: Order [] = [orderDetails]; console.log(orders); const response = await request.post("http://localhost:3004/addOrder/", { data: orders, headers: { "Content-Type": "application/json", }, }); expect(response.status()).toBe(201); }); Code Walkthrough The test imports OrderBuilder to create test data, and the Order interface to ensure type safety.Inside the test, new OrderBuilder().build() generates a complete order object with realistic values using Faker.The generated order is wrapped in an array, orders: Order[] = [orderDetails], as the API expects a list of orders. A console log statement is added to display the generated order in the console.A POST request is sent to the endpoint using Playwright’s request fixture, with the order payload passed in the data field and the appropriate Content-Type header.The test validates that the response status is 201, confirming that the order was successfully created. Test Execution Before running the test, start the RESTful e-commerce application using Docker by running the following command from the terminal: Plain Text docker compose -f docker-compose-ecommerce.yml up -d The test can be executed by running the following command from the terminal: Plain Text npx playwright test tests/post-api-builder-test.spec.ts The following is the output of the test execution: The order details generated using the Builder design pattern are printed on the console with fake data and are used as the request payload in the POST /addOrder test. Writing automated tests by combining generated fake data with selectively updated static values. In the previous test scenario, all order details were generated using the Faker library. However, in real testing scenarios, certain fields may require static values. The Builder Pattern supports this by allowing specific fields to be overridden with static data, while the remaining fields continue to be generated dynamically using Faker. TypeScript test("Add Specific Order details using Builder Design Pattern", async ({ request }) => { const orderDetails = new OrderBuilder().withUserID("56").withProductName("Donuts").build(); const orders: Order [] = [orderDetails]; console.log(orderDetails); const response = await request.post("http://localhost:3004/addOrder/", { data: orders, headers: { "Content-Type": "application/json", }, }); expect(response.status()).toBe(201); }); In this test, the user_id and product_name fields are explicitly set using the withUserID() and withProductName() functions. While the Builder generates the rest of the order details using the Faker library, these two fields are overridden with the static value provided in the test. Let’s execute the test again and check the output: In the above screenshot, it can be seen that the order details are generated successfully using the Faker library; however, the value for user_id is set to "56" and product_name is set to "Donuts," as these were explicitly provided as static values for those fields. Learn how to use the Builder Design Pattern in Java with a Datafaker library to generate test data for automated testing. Summary The Builder Design Pattern is really helpful for creating clean, flexible, and maintainable test data in API automation. When combined with Faker, it enables the generation of realistic data while still allowing specific fields to be customized as needed. There are multiple ways to supply test data in API automation for POST API testing, such as using JSON files or directly generating data with the Faker library in the request payload without the Builder Pattern. However, the choice of approach depends on the application under test, the level of flexibility required, and how the test framework is designed. Happy testing!

By Faisal Khatri DZone Core CORE
When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation
When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation

TypeScript can make an LLM integration look safer than it is. A function may promise Promise<Classification> and every branch may compile under strict settings, yet none of those guarantees prove that a model returned a valid Classification. TypeScript annotations are erased during compilation and do not alter runtime behavior, so data crossing an AI boundary remains untrusted until executable validation proves otherwise. The practical goal is a pipeline in which model output becomes domain data only after passing a runtime contract. Static Types Stop at the Model Boundary A type assertion immediately after JSON parsing suppresses compiler uncertainty without establishing any runtime fact. Parsed data can contain missing fields, unexpected strings, invalid ranges, or extra properties, while an assertion simply tells TypeScript to accept the declared shape. Because unknown requires narrowing before operations are permitted, it is the safer representation for an untrusted boundary. TypeScript type Classification = { label: "bug" | "feature" | "question"; confidence: number; }; const candidate: unknown = JSON.parse(raw); const result = candidate as Classification; The final line creates a compile-time claim with no runtime check. Risk rises when the result controls database writes, tool calls, or authorization-sensitive workflows. A reliable boundary keeps the value as unknown until validation establishes the required structure. Make the Schema the Executable Contract A runtime schema library closes the gap between erased TypeScript types and actual JavaScript values. Zod is designed to define runtime schemas while inferring static TypeScript types from the same definition, which allows one artifact to serve both validation and compile-time ergonomics. z.strictObject() is especially useful at an LLM boundary because unexpected keys become validation failures rather than silently extending the accepted surface. TypeScript const ClassificationSchema = z.strictObject({ label: z.enum(["bug", "feature", "question"]), confidence: z.number().min(0).max(1), rationale: z.string().min(1).max(800), }); type Classification = z.infer<typeof ClassificationSchema>; The schema carries runtime constraints that a TypeScript type alone cannot enforce. The enum limits labels, numeric checks enforce the confidence interval, string bounds constrain explanations, and strict object handling rejects undeclared fields. The inferred Classification type follows the schema instead of being maintained separately, reducing static/runtime drift. Zod documents z.infer for static inference and structured errors for failed parses. Parse Before Data Enters Domain Logic Validation works best when it is treated as a boundary operation rather than scattered defensive checks. Raw model text first has to satisfy JSON syntax, then the resulting JavaScript value has to satisfy the runtime schema. Only the successfully parsed value should enter business logic. safeParse() returns a discriminated result that contains either validated data or a ZodError, which makes rejection paths explicit without using exceptions for normal validation flow. TypeScript function parseClassification(raw: string): Classification { let candidate: unknown; try { candidate = JSON.parse(raw); } catch { throw new Error("Model output is not valid JSON"); } const parsed = ClassificationSchema.safeParse(candidate); if (!parsed.success) { throw new Error(z.prettifyError(parsed.error)); } return parsed.data; } The important property is provenance. Classification comes from parsed.data after runtime validation, not from a cast. Validation errors can also remain structured telemetry because Zod exposes issue codes, paths, and messages identifying contract violations. Zod additionally provides z.prettifyError() when a human-readable representation is needed. Structured Output Reduces Syntax Risk, Not Trust Risk Modern LLM APIs can constrain generation against JSON Schema. OpenAI Structured Outputs, for example, is documented as enforcing supplied JSON Schema rather than merely producing syntactically valid JSON, and the current API distinguishes structured output from older JSON mode. That substantially reduces malformed payloads and schema-shape errors. It does not remove the need for an application-side trust boundary, because structured responses can still be interrupted, refused, or semantically wrong even when their shape is valid. OpenAI explicitly documents incomplete responses, refusal handling, and the possibility of mistakes inside structured outputs. Zod 4 can convert schemas directly to JSON Schema with z.toJSONSchema(), making it possible to drive model-side constrained generation and application-side validation from the same source definition. The conversion targets JSON Schema Draft 2020-12 by default, although not every Zod feature is representable as JSON Schema; transforms, Date, Map, Set, and several other constructs require different handling. That limitation favors separating wire contracts from richer domain representations. The model-facing schema can remain JSON-native, while post-validation code converts ISO strings into Date objects, resolves identifiers, or calculates derived fields. Zod distinguishes schema input and output types and documents that some transformations cannot be soundly represented in JSON Schema. TypeScript const responseSchema = z.toJSONSchema(ClassificationSchema); const response = await client.responses.create({ model: modelName, input: prompt, text: { format: { type: "json_schema", name: "classification", strict: true, schema: responseSchema, }, }, }); Schema-constrained decoding and runtime validation solve different problems. Provider-side constraints narrow generation; the local parser verifies what reached the application boundary. Both layers remain useful when responses are cached or replayed, multiple providers feed the same pipeline, or tests bypass generation. JSON Schema defines structure and constraints, while validation still requires a validator where data is consumed. Model Business Invariants Explicitly Structural validity is necessary but insufficient. A payload can satisfy field types while violating domain rules. A confidence value within range does not prove that the classification is correct, a valid identifier does not prove that the referenced record exists, and a syntactically valid tool argument does not prove that an action is authorized. Structured Outputs documentation similarly notes that schema-conforming responses can still contain mistakes. Runtime schemas should therefore encode deterministic invariants while leaving truth, authorization, and external-state checks to domain services. Cross-field rules belong in the executable contract when they are deterministic. A routing decision, for example, may require an escalation reason whenever the model chooses an escalation action. Zod refinements make such conditions enforceable without widening downstream code with repeated checks. TypeScript const DecisionSchema = z.strictObject({ action: z.enum(["answer", "escalate"]), answer: z.string().optional(), reason: z.string().optional(), }).refine( value => value.action !== "escalate" || Boolean(value.reason), { error: "Escalation requires a reason" } ); This keeps deterministic validation close to the contract without implying that a schema can establish facts outside the payload. Database existence, permissions, rate limits, and transactional constraints remain separate runtime responsibilities. JSON Schema is defined around the structure and constraints of a JSON instance, making it a format contract rather than external-state verification. Fail Closed and Treat Validation as a Signal A production pipeline should not blindly coerce invalid output into the expected type. Silent defaults can turn model failures into plausible data. Invalid output is better treated as a controlled failure with bounded retry, explicit refusal and incomplete-response branches, and validation telemetry. Zod provides machine-readable issues, while structured-output APIs expose interruption and refusal states before domain execution. A model contract also benefits from explicit versioning. Schema changes such as renamed enum values, newly required fields, or tighter bounds can invalidate cached outputs and replayed events even when current generation is correct. Recording a schema identifier or application contract version beside generated data makes compatibility decisions explicit and prevents historical payloads from being interpreted under a newer contract. JSON Schema supports identifiers and dialect declarations for machine-readable schema metadata. The central engineering rule is simple: TypeScript types describe what trusted code may assume, not what an LLM actually produced. Untrusted AI output should enter the system as unknown, cross an executable runtime schema, and become a domain type only after successful validation. Provider-side structured output can reduce formatting failures, but it cannot replace local validation or domain checks. A pipeline built around that boundary preserves TypeScript’s strongest benefit without confusing compile-time confidence for runtime truth, and it converts probabilistic model output into data that deterministic application code can safely reason about.

By Bhanu Sekhar Guttikonda DZone Core CORE
Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint

When engineering teams build distributed systems, they naturally reach for REST over HTTP/1.1 with JSON payloads. JSON is readable, universally supported, and trivially easy to debug with any browser or proxy tool. For early-stage services handling modest traffic, that convenience is a genuine engineering asset. But as microservice topologies scale toward hundreds of nodes handling tens of thousands of concurrent requests, text-based serialization frequently evolves from a minor convenience into a measurable architectural bottleneck. CPU utilization climbs, p99 latencies widen, and intra-zone bandwidth costs quietly compound across every internal service hop. Transitioning internal service-to-service communication to Protocol Buffers (Protobuf) over HTTP/2 via gRPC is one of the most effective and high-leverage responses to this problem. This article breaks down exactly why JSON degrades at scale, how Protobuf's binary wire format addresses those root causes, and how to execute a zero-downtime migration without breaking your running services. The Hidden Cost of Text-Based Serialization at Scale To understand why JSON degrades at high throughput, you have to look past network bandwidth and examine CPU behavior directly. JSON is a text-based, schema-less format. Every time a microservice ingests a JSON payload, the runtime must allocate memory on the heap, parse raw strings, map keys to internal structs via reflection, and convert values to their respective data types. At low volumes, this parsing overhead is negligible. At enterprise scale, it compounds into a real problem across two distinct dimensions. 1. CPU-Bound Allocation and GC Churn In languages with managed memory runtimes, such as Go, Java, and Node.js being the most common in microservice architectures, parsing thousands of large JSON strings per second causes significant garbage collection pressure. Each incoming payload generates a burst of short-lived string allocations on the heap. The garbage collector is forced to run more frequently to reclaim this memory, and in runtimes that use stop-the-world collection phases, this directly spikes p99 tail latencies. The problem is not that JSON parsing is intrinsically slow on a single call. The problem is that at scale, thousands of calls per second accumulate into sustained allocation pressure that the GC cannot absorb cleanly. 2. Network Payload Bloat JSON payloads are structurally verbose because every single message must explicitly include field names as strings. Consider this representative internal service message: JSON { "transaction_id": "tx_9988112233", "account_status": "ACTIVE", "retry_count": 3 } On the wire, this payload consumes roughly 85 bytes. More than half of those bytes (over 50) are dedicated purely to transmitting key metadata: the strings "transaction_id", "account_status", and "retry_count". These keys carry no runtime information that the receiving service doesn't already know from its own code. They are structural overhead repeated on every single message. Multiply this across millions of internal RPC calls through a service mesh and you are looking at gigabytes of redundant key data transmitted intra-zone every day. That's bandwidth you are paying for and CPU cycles you are spending to parse, without gaining any informational value. The Mechanics of the Binary Shift: Why Protobuf Moves the Needle Protocol Buffers eliminate text overhead by relying on a strict Interface Definition Language (IDL) and a highly compressed binary wire format. Instead of transmitting field names, Protobuf assigns each field a unique integer tag. When a message is serialized, the keys are stripped out entirely. The wire representation of any field is just its integer tag combined with a wire type identifier, followed by the raw data bytes. The equivalent of the JSON example above looks like this as a .proto definition: ProtoBuf syntax = "proto3"; message AccountTransaction { string transaction_id = 1; string account_status = 2; int32 retry_count = 3; } The same AccountTransaction message with the values tx_9988112233, ACTIVE, and 3 serializes to approximately 24 bytes on the wire — a reduction of roughly 72% compared to the JSON equivalent. Varints and Length-Delimited Encoding Two specific encoding techniques drive most of that size reduction. Varints (Variable-Length Quantities): Standard integers occupy a fixed 4 or 8 bytes regardless of their actual value. Protobuf varints use the most significant bit as a continuation flag, meaning small integers consume fewer bytes than large ones. The value 3 in the retry_count field above occupies exactly one byte on the wire. For the high-frequency small counters and status codes typical in microservice messages, this is a consistent win. Length-delimited encoding: Strings and nested messages are encoded with an explicit byte-length prefix followed by the raw byte block. The parser reads the tag, reads the length, and copies the exact memory block directly. There is no tokenization, no string-splitting, and no key-to-field mapping via reflection. This direct memory copy approach is what makes Protobuf deserialization significantly faster than JSON parsing in practice. Benchmarks from the go_serialization_benchmarks project (available on GitHub) consistently show Protobuf outperforming standard library JSON by 4–8x in throughput on typical message shapes. Architectural Trade-Offs: When to Move and When to Wait Migrating to Protobuf is not a universal improvement. It introduces distinct operational trade-offs that teams should evaluate honestly before committing. MetricJSON over HTTP/1.1Protobuf over HTTP/2 (gRPC)Human readabilityNative — clear text in proxy logsRequires compiled schemas or tooling like grpc-curl or protoscope to inspectSchema enforcementOptional — JSON Schema is separate from the formatMandatory — enforced at build time via protoc compilationNetwork efficiencyLow — verbose string keys on every messageHigh — packed binary tag-value pairs, no key transmissionCPU utilizationHigh — heap allocation, reflection, and string parsingLow — direct memory copies and varint arithmeticDebugging overheadLow — any HTTP tool worksHigher — binary streams require schema-aware toolingSchema registry costNone — ad hoc contract managementReal — .proto files must be versioned and distributed across teams The debugging and schema-management costs deserve emphasis because they are frequently underestimated. In a JSON-based system, any engineer can inspect a live request in a proxy log or with curl. In a Protobuf system, you need the compiled schema available to decode what is on the wire. Teams that invest in a proper schema registry and standardize on tools like grpcurl absorb this cost smoothly. Teams that don't will find debugging production issues significantly harder. The Edge vs. Mesh Topology Split The most pragmatic migration approach keeps JSON at the public API boundary while adopting Protobuf exclusively for internal service-to-service traffic. The API Gateway acts as the translation layer: it terminates public-facing REST/JSON requests from browsers and mobile clients, validates the incoming payloads, and transforms them into strongly-typed Protobuf messages before routing them across the internal service mesh. Public consumers never see binary formats. Internal services get the full efficiency benefit. This topology preserves external interoperability while capturing the performance gains where they matter most, which is inside the mesh, where requests fan out across many hops. Executing a Zero-Downtime Migration The core challenge in any serialization migration is that you cannot atomically redeploy every service simultaneously. Services must continue communicating during the transition. The following phased approach handles this safely. Phase 1: Dual-Stack Services Update each internal service to accept both JSON and Protobuf requests simultaneously, using the Content-Type header to distinguish them (application/json vs. application/x-protobuf). This is the strangler fig pattern applied to serialization. No existing traffic breaks, and you can validate Protobuf behavior against live traffic without fully cutting over. Phase 2: Canary Routing Once dual-stack services are deployed, route a small percentage of internal traffic, start with 1–5%, to the Protobuf path. Monitor p99 latency, error rates, and deserialization failure metrics at the canary boundary. This is the moment where schema mismatches and field mapping errors surface, and it is far better to find them at 1% traffic than at 100%. Phase 3: Full Cutover and JSON Deprecation After the canary validates correctly over a sufficient observation window (typically one to two release cycles), shift all internal traffic to Protobuf. Maintain the JSON code path for a deprecation period to support any lagging consumers, then remove it once all services confirm clean Protobuf-only communication. Mapping JSON Structures to Proto3 When moving from a schema-less JSON environment to a typed Proto3 environment, data structures need explicit definition. Here are the most common mapping decisions. Primitive and Complex Types Numbers: Map floating-point values to double or float. Map integers to int32, int64, or uint32. If values can be negative and small (common for status codes or offsets), use sint32 or sint64, which apply ZigZag encoding to make negative varints more compact.Arrays: Represent repeated values with the repeated keyword.Maps: Use the native map<string, string> syntax. Note that map fields cannot be marked as repeated. Bootstrapping Proto Definitions From Existing Payloads When you are migrating an existing system with dozens or hundreds of active message models, writing .proto definitions by hand from legacy JSON schemas is tedious and error-prone, especially when the source payloads contain deeply nested objects, polymorphic arrays, or inconsistent field naming conventions. A practical shortcut during the early scaffolding phase is to use a JSON-to-Protobuf converter utility. You feed in a representative sample payload, and it generates a baseline .proto definition that matches the field names, infers appropriate types, and assigns initial field numbers. The output is not final. You will still need to review type choices, apply sint32/sint64 where appropriate, and add optional markers for nullable fields, but it eliminates the mechanical first pass and lets engineers focus on the decisions that actually require judgment. This is particularly useful when onboarding a new team member to the migration or when tackling a legacy service whose JSON schema was never formally documented. Handling the Absence of Native Nulls Proto3 does not have a native null state for primitive types. Unset fields default to their zero value — empty string "" for strings, 0 for integers. In systems where an unset field and a zero-value field carry different semantic meaning, this distinction matters. Two approaches address this. The first is the optional keyword, which wraps the primitive in a field-presence tracker that lets the receiver distinguish "this field was not set" from "this field was set to zero": ProtoBuf syntax = "proto3"; message PaymentRecord { string payment_id = 1; optional int32 discount_percentage = 2; // Distinguishes "no discount" from "0% discount" } The second is Google's well-known wrapper types, which provide nullable primitives at the cost of a more verbose message structure: ProtoBuf import "google/protobuf/wrappers.proto"; message ExtendedTransaction { string id = 1; google.protobuf.StringValue middle_initial = 2; // Nullable string } For most use cases, optional is the cleaner choice. Wrapper types are useful when you need to nest nullable primitives inside repeated fields or maps. Managing Schema Evolution Without Breaking Running Services In a distributed environment with independent deployment cycles, schema changes are inevitable and dangerous if handled carelessly. Protobuf addresses this through strict backward and forward compatibility rules, but only if you respect two absolute constraints. Never change field numbers. The binary parser maps incoming bytes to fields purely by tag integer. If you change a field number on a deployed message, existing services will misread the data silently and without error. Never change the wire type for an existing tag. If a field needs to change from int32 to string, you must deprecate the old tag and introduce a new field with a new field number. Beyond those hard rules, backward compatibility allows you to add new fields freely. A service that receives a message with an unknown field number will simply ignore it. This means services can be updated independently and out of order without breaking communication, which is a critical property in a rolling deployment environment. Graceful Deprecation in Practice When phasing out an existing field, mark it with the deprecated option rather than deleting it. This preserves binary compatibility for services still reading the field while alerting downstream teams through compiler warnings: ProtoBuf message UserContext { string user_id = 1; string legacy_token = 2 [deprecated = true]; // Superseded by session_hash; remove after Q3 cutover string session_hash = 3; } Do not reuse the field number after deprecation. Reserve it explicitly using the reserved keyword to prevent future developers from accidentally reusing a tag that old binary data may still contain: ProtoBuf message UserContext { reserved 2; reserved "legacy_token"; string user_id = 1; string session_hash = 3; } Concrete Implementation: Deserializing Protobuf in Go The following example shows a typical internal Go service handler receiving and deserializing a Protobuf message using the current v2 API (google.golang.org/protobuf/proto). Note: the v1 package (github.com/golang/protobuf) is archived and should not be used in new code. Go package main import ( "fmt" "log" "time" "google.golang.org/protobuf/proto" pb "path/to/generated/pb" // Pre-compiled .pb.go output from protoc ) func processPayload(rawBytes []byte) (*pb.AccountTransaction, error) { transaction := &pb.AccountTransaction{} // Unmarshal reads binary data directly into the struct without string parsing if err := proto.Unmarshal(rawBytes, transaction); err != nil { return nil, fmt.Errorf("deserialization failed: %w", err) } if transaction.GetTransactionId() == "" { return nil, fmt.Errorf("missing required field: transaction_id") } return transaction, nil } func main() { // This binary slice is the wire encoding of: // transaction_id: "tx_9988112233", account_status: "ACTIVE", retry_count: 3 // Generated via proto.Marshal on the populated AccountTransaction struct sampleBinaryPayload := []byte{ 10, 13, 116, 120, 95, 57, 57, 56, 56, 49, 49, 50, 50, 51, 51, 18, 6, 65, 67, 84, 73, 86, 69, 24, 3, } start := time.Now() tx, err := processPayload(sampleBinaryPayload) if err != nil { log.Fatalf("processing failure: %v", err) } fmt.Printf("Processed transaction %s in %v\n", tx.GetTransactionId(), time.Since(start)) } The key difference from JSON unmarshaling is in what proto.Unmarshal does not do: it does not tokenize strings, does not map keys via reflection, and does not allocate intermediate string representations. It reads the tag, determines the field type from the compiled schema, and copies raw bytes directly to the target struct field. At high throughput, that distinction in allocation behavior is what drives the difference in GC pressure and tail latency. What This Migration Actually Solves, and What It Does Not Protobuf is not a solution to every distributed systems problem. It will not fix poorly designed service boundaries, reduce round trips caused by chatty interfaces, or compensate for network topology problems. What it specifically addresses is the serialization and deserialization overhead on hot paths where internal services are exchanging high volumes of structured messages. The teams that see the clearest wins are those where profiling has confirmed that serialization CPU time is a meaningful contributor to request latency, and where payload sizes have made bandwidth a real infrastructure cost. If your p99 latency problems trace to database queries, downstream API calls, or lock contention, the Protobuf migration will have minimal impact on those numbers. Start by profiling your highest-traffic internal endpoints. Measure serialization time as a fraction of total request time. Measure payload sizes across a representative sample of production traffic. If the data shows serialization is a genuine bottleneck, the migration is well-justified. If it is not, the operational investment in schema management and tooling upgrades may not pay off on the timeline you need. For the services where it does make sense, the gains are real and durable. Lower CPU utilization, reduced GC pressure, smaller payloads across every internal hop, and strongly typed contracts enforced at build time; these compound over time as traffic grows. Summary The path from JSON to Protobuf is not about chasing a trend. It is a deliberate architectural decision to eliminate serialization overhead on hot internal paths by replacing text parsing with direct binary memory operations. The practical steps are straightforward: audit your highest-traffic internal endpoints, define your .proto schemas with careful attention to field numbering and null semantics, deploy dual-stack services to enable a phased cutover, and establish tooling for schema versioning before your team's first production deployment. The operational costs are real but manageable. Binary streams require schema-aware debugging tools, .proto files need disciplined version management, and the reserved keyword must become part of your deprecation workflow. Teams that treat schema governance as a first-class concern alongside their code absorb these costs smoothly. For distributed systems where internal traffic volume makes serialization overhead measurable, the migration consistently delivers: lower tail latency, reduced bandwidth spend, and contracts that fail loudly at compile time rather than silently at runtime.

By Bansidhar kadiya
Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop

The message left the first service at 2:14 PM and never reached the last one. Between those facts: four pipeline stages, six topics, a pub/sub API moving every record. The engineer on call had Kafdrop open, the offsets looked fine, and nobody could say which stage had eaten the record. That gap is why we built message search for Kafdrop at a hackathon. The setup was familiar from my day job: a platform moving data between pipeline stages over a pub/sub API, with no way to ask where a message went when something breaks. Kafdrop showed partitions and offsets. It couldn't search inside the messages. Kafka has no index. That is the whole problem in one sentence. A topic is an append-only log split across partitions, and the consumer API reads by offset: hand it 41,207, and it returns record 41,207. There is no "find the record containing order-88412." To search, you pick a starting point and read forward until you find what you want or stop. So that is what our feature does, with guardrails that keep the search from hurting the cluster. The interesting part was the caps, the consumer setup, and the SRE agreement. Why a Full Scan Is Not an Option The obvious approach is to read the whole topic and grep. Topics hold days of data, so the whole thing doesn't fit in memory. Reading every record on every search hammers the brokers, and during an incident that is the worst time to add load. Most searches end with a few matches, so nearly all of that work is wasted. The other approach is to mirror every topic into a search engine. That works, and plenty of teams do it. It also means running a second distributed system and explaining index lag during every incident. For a hackathon debugging tool, that was too much machinery. The Design: Seek, Scan, and Stop The feature takes four inputs: a topic, a query string, a start time, and two caps. The start time bounds how far back the search goes. Kafka's offsetsForTimes maps a timestamp to the first offset at or after it per partition, or null when the partition holds nothing that new. The user picks "the last hour" or "since the deploy." The result cap bounds memory: return the first N matches and stop. Debugging usually needs one record, not ten thousand. The scan cap bounds broker load: stop after M records even with no match. Every search becomes a fixed amount of work, whatever the user types. A typo costs M reads. The scan can never grow beyond that. Polls use bounded batches, so the tool never holds more than one page of records at a time. Nothing loads a whole topic. Safety: Assign, Don't Subscribe The consumer setup is where a search tool can quietly cause damage. Three decisions were non-negotiable. First, the search consumer uses assign, not subscribe. Subscribe joins a consumer group, bringing coordination and rebalances. A debugging tool has no business in any of that. Assign hands the consumer a fixed partition list and stays out of group coordination entirely. Second, the consumer never commits offsets. Auto-commit is off, and the code never calls commit. The default config commits automatically, so this is the one that bites: a search tool that advances a production group's offsets is a horror story, and the fix is one config line. Third, the scan cap doubles as a safety control: every search reads at most M records, a worst case SRE can read before approving. The Search Loop Here is the core in Java. The three constants are the whole design: matches to return, records to read in the worst case, records per poll. The values are illustrative; tune them to your topics. Java private static final int RESULT_CAP = 25; private static final int SCAN_CAP = 50_000; private static final int POLL_BATCH = 500; public List<FoundMessage> search(String topic, String query, long startTimeMs) { Properties props = new Properties(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, String.valueOf(POLL_BATCH)); List<FoundMessage> matches = new ArrayList<>(); try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) { List<TopicPartition> partitions = new ArrayList<>(); for (PartitionInfo p : consumer.partitionsFor(topic)) { partitions.add(new TopicPartition(topic, p.partition())); } consumer.assign(partitions); Map<TopicPartition, Long> times = new HashMap<>(); for (TopicPartition tp : partitions) times.put(tp, startTimeMs); for (Map.Entry<TopicPartition, OffsetAndTimestamp> e : consumer.offsetsForTimes(times).entrySet()) { if (e.getValue() != null) consumer.seek(e.getKey(), e.getValue().offset()); else consumer.seekToEnd(Collections.singletonList(e.getKey())); } long scanned = 0; while (scanned < SCAN_CAP && matches.size() < RESULT_CAP) { ConsumerRecords<String, String> batch = consumer.poll(Duration.ofMillis(500)); if (batch.isEmpty()) break; for (ConsumerRecord<String, String> r : batch) { if (++scanned > SCAN_CAP) break; if (r.value() != null && r.value().contains(query)) { matches.add(new FoundMessage(r.topic(), r.partition(), r.offset(), r.timestamp(), r.value())); if (matches.size() >= RESULT_CAP) break; } } } } return matches; } From the top: the config disables auto-commit and fixes the poll batch size. Assign takes a fixed partition list. offsetsForTimes turns the start time into a starting offset per partition; the null branch seeks to the end for partitions with nothing that new. The loop reads forward and stops at whichever cap hits first. Nothing commits, and try-with-resources closes the consumer. Matching is a substring check on the record value. Tombstones carry nulls, so the null check is load-bearing. Shipping It: A Container, Kubernetes, and the SRE Agreement The app ships as a container image: the search service and its config, nothing else. It runs on Kubernetes as a small deployment with tight resource limits, since the result cap already bounds memory. One replica is plenty. YAML apiVersion: apps/v1 kind: Deployment metadata: name: kafdrop-search spec: replicas: 1 selector: matchLabels: app: kafdrop-search template: metadata: labels: app: kafdrop-search spec: containers: - name: search image: registry.example.com/kafdrop-search:1.0.0 resources: requests: memory: "256Mi" cpu: "250m" limits: memory: "512Mi" cpu: "500m" env: - name: KAFKA_BROKERS value: "kafka:9092" The manifest is deliberately boring: one replica, tight memory limits, brokers passed as config. The SRE conversation was short, because the design answered their questions first. The tool only reads: assign instead of subscribe, no offset commits, read-only Kafka credentials. Every search is bounded by the scan cap, so the worst case was a number everyone could read. That agreement mattered more than the code. The caps were the trust. A Debugging Routine That Works First, search the topic for the message using something unique: an order ID, a request ID. Found it? Note the offset and timestamp. Second, check consumer group lag for the downstream stage. If the group consumed past your message's offset, the stage read it, and the problem is in the consumer's logic. If lag is stuck or growing, the consumer is behind, crashed, or wedged on a poison record. Third, look at the consumer: logs around the message's timestamp, error handling, the dead-letter path. The order matters. It separates "the message never arrived" from "the message arrived and something went wrong." Before, step one was guesswork. Now it takes minutes. What We Kept Kafka gives you ordering and durability, not search. Bolting search onto an append-only log means accepting the scan. Make it bounded and boring: seek to a timestamp, read forward in small batches, stop at the first cap. Keep the three decisions that made it safe. Assign instead of subscribe, so the tool never joins a consumer group. Never commit offsets, so reading changes nothing. A scan cap that turns every search into a known quantity of broker work. Get those right, and SRE will let you run it against production. Get them wrong, and you have built a very efficient way to cause your next incident. After the hackathon, the team kept the tool for one job: finding where a message stopped. A search, a lag check, and a look at the consumer, done in minutes. Diagnosis time during incidents fell.

By Shreyamsh Kamate
Introduction to Error Prone: How to Catch Bugs at Compile Time
Introduction to Error Prone: How to Catch Bugs at Compile Time

The Java compiler’s job is to check whether code follows the rules of the language. Trying to remove an element from a collection that can never contain it, or using the wrong letter in a date pattern, does not break those rules, so nothing stops the code from compiling. In short, any code that follows the rules compiles, even when it does not do what its author intended. What Is Error Prone? Error Prone is an open-source static analysis tool that Google built to fill this gap. Unlike most static analysis tools, it does not run as a separate step; it plugs into javac as a plugin. Using the information the compiler produces while analyzing the code, it looks for patterns that follow the rules of the language but are most likely wrong, and reports them as compiler warnings or errors. The idea is simple: a bug costs the least to fix when the code is written. Error Prone catches bugs during compilation, before they reach code review, CI, or production. Google has used the tool on its huge Java codebase for years, but its use is not limited to Google. NullAway, the null safety tool developed by Uber, runs as an Error Prone plugin. Spring Framework 7 checks its own codebase with NullAway during the build. Popular libraries such as Caffeine also use Error Prone in their builds. The examples in this article, which introduces you to Error Prone, are available in this repository. How It Differs From Other Static Analysis Tools The Java world has well-established tools such as SpotBugs, PMD, Checkstyle, and SonarQube. Three key features set Error Prone apart from them: It runs inside the compiler. It needs no separate build step or server. Because it is a plugin for javac, it works with any build tool that calls javac (Maven, Gradle, Bazel, Ant).It knows everything the compiler knows. The analysis runs on the AST that javac builds, after the type attribution and flow analysis phases. This gives Error Prone access to all symbol and type information. For example, it knows exactly what the generic type argument of an expression is, or which overload was chosen.It does not stop at a diagnosis; it suggests a fix. Most checks come with a suggested fix, which can be applied to the source code with a single command. How Does Error Prone Help Developers? The strength of Error Prone is that it can stop code that compiles but behaves incorrectly, right at compile time. Let’s take a closer look at the following example from the official documentation: Java Set<Short> s = new HashSet<>(); for (short i = 0; i < 100; i++) { s.add(i); s.remove(i - 1); } System.out.println(s.size()); This code seems to remove the previous element at each step, so you would expect it to print 1. It prints 100 instead, because the expression i - 1 is an int and is boxed to Integer. Since the Set<Short> contains no Integer, remove removes nothing. And because the remove(Object) signature accepts any type, the compiler does not complain either. Error Prone, however, refuses to compile this code: Plain Text [ERROR] ShortSet.java:[22,21] [CollectionIncompatibleType] Argument 'i - 1' should not be passed to this method; its type int is not compatible with its collection's type argument Short Now let’s look at the following code: Java private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("YYYY-MM-dd"); String reportName(LocalDate date) { return "report-" + FORMATTER.format(date) + ".csv"; } The code looks right when you read it, and it even works correctly for most of the year. However, Y in the pattern does not mean the calendar year; it means the week-based year. The calendar year is written with a lowercase y. When the last days of the year fall into the first week of the next year, the two values diverge. For example, for LocalDate.of(2025, 12, 29) the result is report-2026-12-29.csv, so the date jumps a year ahead. When the bug shows up also depends on the locale. The same code starts producing the wrong year on December 28 in the en-US locale, and on December 29 in the tr-TR locale. For the rest of the year the tests pass, and in code review the difference between YYYY and yyyy is easy to miss. Error Prone recognizes this pattern, stops the compilation and suggests the fix as well: Plain Text [ERROR] ReportDate.java:[16,83] [MisusedWeekYear] Use of "YYYY" (week year) in a date pattern without "ww" (week in year). You probably meant to use "yyyy" (year) instead. Did you mean 'private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");'? Note that in both examples the code is valid Java and compiles without any problem. At best, your IDE shows a warning; the build does not break. Since the code can also pass the tests, the bug can live unnoticed for a long time. With Error Prone, you do not have to rely on anyone’s attention to catch these subtle bugs: the build fails, the error message explains the problem, and it often suggests the fix as well. Extending Error Prone Error Prone is not a closed set of rules. Where the built-in checks fall short, you can add your own rules on the same infrastructure they use. There are two ways to do this: Writing transformation rules with Refaster. Rules of the form “when you see this code, replace it with that” are written as plain Java templates.Writing your own BugChecker. Team-specific bug patterns are defined with the same API that Error Prone uses for its own checks. Refaster Refaster is a refactoring tool that is part of Error Prone, built for large-scale transformations across big codebases. You do not write the rule against an AST API, but in plain Java: “when you see this, replace it with that.” A Refaster rule is an ordinary Java class with at least two methods. @BeforeTemplate defines the pattern to look for, and @AfterTemplate defines the code to put in its place: Java class StringIsEmpty { @BeforeTemplate boolean before(String s) { return s.length() == 0; } @AfterTemplate boolean after(String s) { return s.isEmpty(); } } The template is matched with type information, not as text. That is why both name.length() == 0 and user.getEmail().length() == 0 are caught, while the same expression on a type other than String that also has a length() method is not. By writing more than one @BeforeTemplate, you can combine different patterns that lead to the same result in a single rule. Using a rule takes two steps: The rule class is compiled with the RefasterRuleCompiler plugin, which produces a .refaster file. The plugin lives in the error_prone_refaster artifact and is passed to the compiler with the -Xplugin:RefasterRuleCompiler --out rules.refaster argument.The generated .refaster file is passed to Error Prone with -XepPatchChecks:refaster:<file>. Error Prone writes the matches to a patch file, or applies them directly to the source code with -XepPatchLocation:IN_PLACE. Refaster is ideal for tasks such as migrating from one API to another, removing a deprecated method, or standardizing an idiom within a team. Picnic’s open-source Error Prone Support project also offers a way to run Refaster rules on every build, like a regular Error Prone check. Custom BugCheckers Error Prone’s built-in checks do not cover every rule. Alongside widely shared rules such as “sensitive data like national ID numbers, credit card numbers and email addresses must not be written to logs” or “do not use new BigDecimal(double) for monetary calculations", each team may also have its own rules, such as "this internal API must no longer be called". Error Prone lets you write these rules on the same infrastructure as its built-in checks. A custom check is a Java class that extends BugChecker. It declares which AST nodes it is interested in through the *TreeMatcher interfaces it implements. Error Prone calls the check for each such node, and the check returns a match and an optional fix. The following example implements the sensitive data rule. Although the rule is general, only the team knows which data is sensitive. That is why the team marks fields such as national ID numbers or email addresses with its own @SensitiveData annotation: Java public record Customer( String name, @SensitiveData String nationalId, @SensitiveData String email, @SensitiveData String cardNumber) {} The check reports an error when a log call is given a marked field, or an object whose toString() would print marked fields: Java @AutoService(BugChecker.class) @BugPattern(summary = "Sensitive data must not be written to logs", severity = ERROR) public final class SensitiveDataLogging extends BugChecker implements MethodInvocationTreeMatcher { private static final String SENSITIVE_DATA = "org.jugistanbul.SensitiveData"; private static final Matcher<ExpressionTree> LOGGER_CALL = instanceMethod() .onDescendantOfAny( "java.lang.System.Logger", "java.util.logging.Logger", "org.slf4j.Logger"); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!LOGGER_CALL.matches(tree, state)) { return Description.NO_MATCH; } tree.getArguments().stream() .flatMap(argument -> stringifiedValues(argument, state)) // "..." + x → "...", x .filter(value -> isSensitive(value, state)) .forEach(value -> state.reportMatch( buildDescription(value) .setMessage("'%s' contains sensitive data and must not be written to logs" .formatted(state.getSourceForNode(value))) .build())); return Description.NO_MATCH; } private static boolean isSensitive(ExpressionTree value, VisitorState state) { // customer.email(): the field or accessor itself is annotated var symbol = ASTHelpers.getSymbol(value); if (symbol != null && ASTHelpers.hasAnnotation(symbol, SENSITIVE_DATA, state)) { return true; } // customer: the class, or one of its fields, is annotated, so toString() leaks it var type = ASTHelpers.getType(value); if (type == null || type.isPrimitive() || !(type.tsym instanceof ClassSymbol valueClass)) { return false; } return ASTHelpers.hasAnnotation(valueClass, SENSITIVE_DATA, state) || valueClass.getEnclosedElements().stream() .anyMatch(member -> member.getKind() == ElementKind.FIELD && ASTHelpers.hasAnnotation(member, SENSITIVE_DATA, state)); } // stringifiedValues(...) splits a string concatenation into its operands; see the repo } In the demo’s CheckoutService, the first line passes because it only logs the customer's name, while the other two do not compile: Java LOG.log(Level.INFO, "Order " + orderId + " placed by " + customer.name()); LOG.log(Level.DEBUG, "Order " + orderId + " placed by " + customer); LOG.log(Level.INFO, "Receipt for order " + orderId + " sent to " + customer.email()); Plain Text [ERROR] CheckoutService.java:[25,67] [SensitiveDataLogging] 'customer' contains sensitive data and must not be written to logs [ERROR] CheckoutService.java:[28,90] [SensitiveDataLogging] 'customer.email()' contains sensitive data and must not be written to logs The check looks at the expression passed to the logger, so a value first copied into a local variable (String email = customer.email();) is not tracked; following it would need data-flow analysis. This short class shows all the parts of a custom check: @BugPattern: Defines the rule's name, description, and severity (ERROR or WARNING). The rule can be turned off, or its severity changed, by its class name (-Xep:SensitiveDataLogging:WARN), and it can be suppressed with @SuppressWarnings.Matchers: Ready-made building blocks such as MethodMatchers express conditions like "any method of a System.Logger, java.util.logging or SLF4J logger" with type information, in a single expression.Type and symbol information: ASTHelpers gives access to the symbol and type of the logged value. Annotations are resolved by their fully qualified names, so an annotation with the same name in another package does not get mixed in. A text search cannot do this.@AutoService: Makes the check discoverable through ServiceLoader. Adding the jar that contains the checks to the annotation processor path is enough. This check only reports the error, but checks can also suggest fixes with SuggestedFix. BigDecimalDoubleConstructor in the repository is a short example that suggests BigDecimal.valueOf(double) instead of new BigDecimal(double). Checks are tested with CompilationTestHelper. // BUG: Diagnostic contains: comments in the test source mark the line where an error is expected. For checks that suggest fixes, BugCheckerRefactoringTestHelper compares the output of the fix with the expected source code; BigDecimalDoubleConstructorTest in the repository is an example. Running the Examples All the examples in this article are available in runnable form in the error-prone-in-action repository: ShortSet and ReportDate, which trigger the built-in checks, three custom checks with their tests, and the StringIsEmpty Refaster rule. The repository's README explains which command runs each example. Conclusion The Java compiler checks whether code follows the language rules, not what its author intended. Error Prone fills this gap from inside the compiler. Using javac’s type information, it catches code that compiles but is most likely wrong, and often suggests the fix as well. Where the built-in checks fall short, you can write transformation rules with Refaster and team-specific checks with the BugChecker API. In my view, this approach is more valuable today than ever. As AI coding assistants speed up the pace of writing code, tools that catch bugs at their cheapest moment, at compile time, are turning from a luxury into a necessity.

By Hüseyin Akdoğan DZone Core CORE
ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Modern enterprise applications must process increasing data volumes while guaranteeing low latency, high availability, and predictable performance. While relational databases are essential for transactional workloads and complex queries, some applications do not fit the relational model. Systems that manage millions of user engagements, financial events, or IoT data often need a persistence solution built for distributed environments and horizontal scalability. In these cases, ScyllaDB affords a compelling option for enterprise architects. ScyllaDB is a high-performance, distributed NoSQL database based on the wide-column data model. Inspired by Apache Cassandra and compatible with its query language (CQL), ScyllaDB uses a shard-per-core architecture to maximize hardware efficiency and preserve consistent performance under intensive workloads. When should ScyllaDB be chosen over traditional relational databases or other NoSQL options? This article examines its column-family model, compares it with Cassandra, and shows how to integrate ScyllaDB into a Java enterprise application. Modern enterprise applications require more than basic data storage. They need high throughput, low latency, and horizontal scalability to manage complex workloads. ScyllaDB is a distributed, high-performance NoSQL database based on the wide-column data model, designed for applications that require predictable performance at scale. Companies such as Discord, Expedia, and Comcast use ScyllaDB in real-world scenarios, including messaging platforms, real-time applications, and high-volume data processing. ScyllaDB is especially well-suited for event-driven architectures, IoT platforms, financial systems, and applications with demanding read-and-write workloads. ScyllaDB uses a schema-based approach with Cassandra Query Language (CQL), which features SQL-like syntax, including statements such as CREATE TABLE, INSERT, and SELECT. Beyond primitive types, ScyllaDB supports collections like List, Set, and Map, as well as User-Defined Types (UDTs) for modeling complex data. This flexibility involves trade-offs: unlike relational databases, ScyllaDB uses query-driven data modeling, limits queries on arbitrary fields, and requires careful use of secondary indexes. This article will examine ScyllaDB’s column-family architecture, compare it with Apache Cassandra, review its capabilities and limitations, and show how to integrate ScyllaDB into enterprise Java applications. Setting Up ScyllaDB With Eclipse JNoSQL ScyllaDB supports deployment in cloud environments, on-premises data centers, and local development setups. Teams can select either self-managed or managed cloud services based on their infrastructure needs. In this tutorial, we will use a single ScyllaDB instance with Docker to focus on the data model and Java integration, avoiding the complexity of a distributed cluster. To start ScyllaDB locally, execute the following command: Shell docker run -d --name scylladb-instance -p 9042:9042 scylladb/scylla This command launches a ScyllaDB container and exposes port 9042, the default for Cassandra Query Language (CQL) connections. After initialization, the database is ready to accept application requests. Integrating ScyllaDB With Eclipse JNoSQL Next, determine how the Java application will connect to ScyllaDB. Starting with Eclipse JNoSQL 1.1.19, a dedicated driver provides native ScyllaDB support, enabling standard SQL operations alongside ScyllaDB-specific features. In this example, we use a Java application with Eclipse MicroProfile Config, CDI, and Jakarta JSON Processing. These technologies are common in MicroProfile and Jakarta EE environments, which helps with integration. First, add the ScyllaDB dependency to your Maven project: XML <dependency> <groupId>org.eclipse.jnosql.databases</groupId> <artifactId>jnosql-scylladb</artifactId> <version>${jnosql.version}</version> </dependency> Set the ${jnosql.version} property to Eclipse JNoSQL 1.1.19 or a compatible newer version. Configuring the Database Schema ScyllaDB uses a schema-based approach similar to Apache Cassandra. Developers define keyspaces, tables, column types, and user-defined types explicitly with CQL. In this example, we create a keyspace named developers, two tables for people and movies, and several user-defined types. Eclipse JNoSQL supports providing initialization queries through MicroProfile Config. Add the following properties to META-INF/microprofile-config.properties: Properties files jnosql.column.database=developers jnosql.scylladb.query.1=CREATE KEYSPACE IF NOT EXISTS developers WITH replication = {'class': 'NetworkTopologyStrategy', 'replication_factor': 1}; jnosql.scylladb.query.2=CREATE COLUMNFAMILY IF NOT EXISTS developers.Person (id bigint PRIMARY KEY, name text, phones list<text>); jnosql.scylladb.query.3=CREATE TYPE IF NOT EXISTS developers.director (name text, movies set<text>); jnosql.scylladb.query.4=CREATE COLUMNFAMILY IF NOT EXISTS developers.Movie (name text PRIMARY KEY, age int, director FROZEN<director>); jnosql.scylladb.query.5=CREATE INDEX IF NOT EXISTS ageIndex ON developers.Movie(age); jnosql.scylladb.query.6=CREATE TYPE IF NOT EXISTS developers.money (currency text, amount decimal); jnosql.scylladb.query.7=CREATE TYPE IF NOT EXISTS developers.headquarter (city text, country text); This configuration highlights multiple key points. CQL is similar to SQL, using statements likeCREATE, explicit types, and primary keys. ScyllaDB supports collections such as list and set, allowing you to represent multiple values without extra tables. User-defined types (UDTs) group related attributes into structured objects, such as the director type. The Movie table uses FROZEN<director>. In CQL, FROZEN stores the UDT as a single value, preventing independent modification of individual fields. We also created a secondary index on the age column. Although ScyllaDB supports secondary indexes, their effectiveness depends on the workload, cardinality, and query types. Do not treat them as equivalent to relational database indexes or as a substitute for proper partition-key design. Defining database schemas through application configuration works for tutorials but isn't recommended for production. Manage schema evolution separately using version-controlled migration tools such as Liquibase, which supports ScyllaDB via its Cassandra extension. This approach separates application deployment from schema changes and improves control over database updates. Mapping Entities and User-Defined Types With the database schema defined, we can create the Java models. We start with Movie, representing a ScyllaDB entity, and Director, representing a user-defined type. Java @Entity("Movie") public class Movie { @Id("name") private String name; @Column private Integer age; @Column(udt = "director") private Director director; } public class Director { @Column private String name; @Column private Set<String> movies; } The Movie entity uses the standard Jakarta NoSQL mapping approach with @Entity, @Id, and @Column. The director attribute maps to a ScyllaDB user-defined type via @Column(udt = "director"). During serialization and deserialization, Eclipse JNoSQL uses the ScyllaDB driver to convert between the Java object and its CQL UDT representation. A UDT is similar to a structured JSON object that groups related fields, but it's a strongly typed CQL value defined in the schema. The Set<String> field in Director demonstrates ScyllaDB’s native support for collections, allowing you to model a director’s movie titles without a separate relational table. Next, we will define the Person entity: Java @Entity("Person") public class Person { @Id("id") private long id; @Column private String name; @Column private List<String> phones; } The phones attribute demonstrates another collection type ScyllaDB supports: list<text>. Eclipse JNoSQL maps Java List<String> directly to the corresponding CQL collection without extra converters or custom serialization. These examples show how ScyllaDB combines a schema-based model with support for structured types and collections. Eclipse JNoSQL offers familiar mapping annotations, permitting applications to use ScyllaDB’s native features. However, object mapping convenience does not replace the need for query-driven data modeling. In distributed databases like ScyllaDB, partition keys, access patterns, and data distribution remain essential architectural considerations. Running the Application: Jakarta NoSQL and Jakarta Data Once you configure the database and map entities, the next step is to interact with ScyllaDB from Java. Eclipse JNoSQL provides two complementary approaches: Jakarta NoSQL, a template-based API for NoSQL databases, and Jakarta Data, which uses the Repository pattern. Both integrate with CDI, letting developers inject persistence components into applications running on either Java SE with CDI or Jakarta EE application servers. Jakarta NoSQL: The Template Approach The first approach uses Jakarta NoSQL with the ColumnTemplate interface, offering a consistent API for wide-column databases. Developers can insert, update, delete, and retrieve entities without interacting directly with the database driver. Java @Inject ColumnTemplate template; For example, you can create a Person entity, insert it, and retrieve it using a fluent query API: Java Person person = Person.builder() .withId(1L) .withName("Ada Lovelace") .withPhones(List.of("234", "432")) .build(); template.insert(person); Optional<Person> result = template.select(Person.class) .where("id").eq(1L) .singleResult(); The entity mapping automatically handles the Java List<String> and its corresponding CQL collection, so you don't need extra serialization code to persist phone numbers. The Template approach is useful when developers need explicit control over persistence operations, want to build queries programmatically, or prefer a consistent API across NoSQL implementations. Jakarta Data: The Repository Approach The second approach uses Jakarta Data and applies the Repository pattern to simplify persistence. Developers define an interface, and Eclipse JNoSQL supplies the implementation. Consider our PersonRepository: Java @Repository public interface PersonRepository extends CrudRepository<Person, Long> { } This interface provides standard CRUD operations, such as save, findById, and deleteById. The repository can be injected with CDI and used directly in the application: Java @Inject PersonRepository repository; repository.save(person); Optional<Person> result = repository.findById(1L); Jakarta Data also supports query methods derived from method names, allowing developers to express queries without writing implementations. MovieRepository demonstrates this capability and exposes ScyllaDB-specific functionality through its dedicated interface: Java @Repository public interface MovieRepository extends ScyllaDBRepository<Movie, String> { List<Movie> findByAge(Integer age); @CQL("SELECT * FROM developers.Movie") List<Movie> findAllQuery(); } The findByAge method demonstrates query derivation, while the @CQL annotation lets you execute native Cassandra Query Language statements. In this example, the age column has a secondary index, so you can query movies by age without using the partition key. However, query derivation does not remove ScyllaDB’s querying restrictions. Repository methods must match queries supported by the schema and indexes. Retrieving all records is useful for demonstrations but should be used cautiously in production with large datasets. Beyond Standard CRUD Operations While Jakarta NoSQL and Jakarta Data simplify common persistence operations, ScyllaDB integration extends beyond standard repositories and templates. Eclipse JNoSQL offers ScyllaDBTemplate, a specialized implementation that exposes database-specific features while maintaining the familiar Java programming model. With this integration, developers can: Control consistency levels: Specify Cassandra-compatible consistency levels, such as ConsistencyLevel.ONE, to balance consistency, latency, and availability.Execute native CQL: Run database-specific queries directly when standard abstractions are insufficient, including those using ScyllaDB-specific features.Work with structured data: Map collections such as List and Set, as well as user-defined types, without manually converting Java objects to CQL values.Choose the right abstraction: Use the vendor-neutral ColumnTemplate for general persistence, or ScyllaDBTemplate for additional database control. For instance, the specialized template supports an operation such as: Java scyllaDBTemplate.save(person, ConsistencyLevel.ONE); A key architectural feature of Eclipse JNoSQL is that abstraction does not mean losing access to database-specific capabilities. Developers can use standardized APIs for common operations and still access native functionality when needed. Jakarta NoSQL and Jakarta Data complement each other, offering different ways to organize persistence logic. The Template approach provides explicit, flexible interaction, while the Repository approach emphasizes declarative data access and separation of concerns. Both benefit from CDI integration, allowing you to use the same persistence components in standalone Java applications, microservices, or Jakarta EE environments. The choice depends on the application’s architectural requirements, but the underlying ScyllaDB capabilities and data-modeling constraints remain the same. Conclusion ScyllaDB is a strong choice for enterprise architects, especially for applications that demand high throughput, consistent latency, and horizontal scalability. Its schema-based wide-column model, support for collections and user-defined types, and compatibility with Cassandra Query Language provide a familiar and robust solution for distributed data persistence. However, to make informed architectural decisions, it's important to understand its query limitations, secondary indexes, and data-modeling trade-offs. Source: https://github.com/JNOSQL/demos-se#scylla.

By Otavio Santana DZone Core CORE
Member Spotlight: Shai Almong
Member Spotlight: Shai Almong

What does it take to build and sustain an open-source project for more than a decade? For Shai Almog, creator of Codename One, it takes a willingness to challenge conventional approaches to software development and a continued commitment to the developers who rely on the work. I recently caught up with Shai to discuss the inspiration behind Codename One, the realities of maintaining an open-source project, and his perspective on how the Java ecosystem has evolved over the years. Check it out below! 1. What is Codename One, and what originally inspired you to create it? Codename One is what we always wanted Java to be: write once, run anywhere, without accepting the lowest common denominator. It’s what you would get if Spring Boot, Flutter, Go, and Node.js had a baby that inherited the best qualities of each. You get Java’s mature ecosystem, Flutter-style control over the UI/portability, Go-like native binaries and footprint, and the full-stack client/server connection people associate with Node.js. With Codename One, one Java codebase can target iOS, Android, macOS, Windows on x64 and ARM64, Linux on x64 and ARM64 with either glibc or musl, and even the browser. A small self-contained desktop GUI application can be around 4–5 MB, with no JVM to install. Underneath, Codename One uses different pipelines for different targets. On our ahead-of-time compiled platforms, ParparVM analyzes the reachable Java bytecode, removes unused code, translates what remains to C, and hands the result to the platform’s native compiler. Codename One also provides the portability libraries, UI toolkit, tests, theming, and build system needed to handle the ugly platform-specific details. We don’t pretend every platform is identical. Our builder architecture assembles the native pieces each application needs, so developers can use platform-specific capabilities without fragmenting the entire codebase. The original inspiration was frustration with Java’s unfulfilled promise. Java gave us portability, but conventional Java application deployment became increasingly heavy. We wanted the language and ecosystem without requiring a large runtime or giving up native performance, platform access, or control of the UI. Now we’re taking that architecture to the backend. The goal is to bring the startup time, footprint, and native compilation work we developed for constrained devices into serverless and microservice workloads. I want Java developers to get the full-stack productivity they expect from Spring Boot, with deployment economics closer to Go and Node.js. 2. Codename One has been around for more than a decade. What has kept you motivated? The community is the biggest reason. People have built businesses and products on Codename One. When someone has trusted your work with something that important, walking away isn’t an option. For a long time, competing in this market was brutal. Our competitors were not normal startups. They were Google, Facebook, Microsoft, and companies with teams larger than our entire community. There was a limit to how much a small team could build, test, document, and support. Agentic development changed that equation. It lets us scale engineering work in a way that simply wasn’t possible a few years ago. We now maintain an enormous cross-platform test matrix and can move at a pace that is competitive with much larger organizations. On most feature dimensions, I would argue that we are already ahead of the big-name alternatives. We still have gaps. We’re a small team, and pretending otherwise would be ridiculous. But our size is also an advantage. The person reading a bug report can be the same person who changes the compiler. We can respond to developers in hours where a large company may need three teams, a quarterly roadmap, and permission from a product manager. The other reason is simpler: we love Java, and we use the competing tools. Every time we do, we run into one of the compromises Codename One was created to remove. 3. What’s one of the biggest misconceptions developers have about maintaining an open source project? That maintaining open source is mostly about accepting code contributions. A pull request looks like free work from the outside. For a maintainer, it can be the beginning of a large amount of work. Is the code correct? Does it meet the project’s standards? Does it work on every target? Who maintains it five years later? How do you tell a volunteer who spent a week on something that the design is wrong? How many rounds of changes can you reasonably ask them to make? We recently stopped accepting outside pull requests. AI wasn’t the reason. If anything, AI improved the baseline quality of many contributions. It also made some of them enormous, because generating another thousand lines became almost free while reviewing those thousand lines did not. The real problem was validation. Codename One currently has more than 60 GitHub Actions workflow files. A small framework change can affect Android, iOS, JavaScript, desktop, bytecode translation, native compilation, and screenshot baselines. That matrix represents roughly $15,000 worth of monthly CI capacity, which GitHub currently provides to us. At that point, validating and repairing an outside patch often took longer than implementing the confirmed change ourselves. So today we ask people to contribute through reproducible issues, benchmark counterexamples, design discussions, testing, and documentation feedback. Those contributions are often more valuable than code because they expose problems we cannot reproduce in our own environments. Also sorry for all the GitHub Actions downtime ;-) 4. You’ve watched Java and the broader development ecosystem evolve considerably. What changes have surprised you the most? The biggest surprise is that Java effectively surrendered the idea of being small. GraalVM is a remarkable piece of engineering, so we aren’t literally alone (although it's a very different project that hasn't really taken the same direction and hasn't taken it as far). But mainstream Java spent years treating bigness as evidence of seriousness: larger runtimes, larger frameworks, more dynamic machinery, longer warmups, and more memory. The industry began treating that weight as inevitable. I'm not against comprehensive/large; Codename One itself is HUGE... But not in runtime, just in API and scope. Most successful newer platforms moved in the opposite direction. Go made self-contained native binaries normal. Node.js made application deployment almost trivial. Mobile and serverless made startup time and memory consumption economically important again. Java largely responded by optimizing large systems rather than questioning why every system needed to be large. Modules are a good example. They help organize and encapsulate a large dependency graph. They do not eliminate that graph or turn it into a small, closed-world native program. Codename One puts a real Java GUI application or full server into a roughly 5 MB binary. What surprises me is not that this works. We have spent years proving that it works. What surprises me is how lonely that position still is. Java could be one of the best languages for small native applications and low-cost serverless workloads. Most of the ecosystem simply stopped trying to make that happen and let Go eat our lunch. 5. After spending so much of your career in technology, what do you enjoy doing when you completely step away from a screen? Completely step away from a screen? I’m probably the wrong person to ask. I just got back from Thailand with my kids. We had a wonderful time. I also had my laptop with me and was doing pull requests on the beach. This is what I enjoy doing. I don’t have an unwind button. Vacations often leave me more exhausted than work because sitting still doesn’t recharge me. If I have an idea and I can build it, fix it, or argue about it with another developer, that is how I unwind. Explore more of Shai's content here.

By Dominique Pugh

Monthly Top JavaScript Experts

expert thumbnail

John Vester

Senior Staff Engineer,
Marqeta

IT professional with 30+ years expertise in app design and architecture, feature development, and project and team management. Currently focusing on establishing resilient cloud-based services running across multiple regions and zones. Additional expertise architecting (Spring Boot) Java and .NET APIs against leading client frameworks, CRM design, and Salesforce integration.
expert thumbnail

Justin Albano

Software Engineer,
IBM

I am devoted to continuously learning and improving as a software developer and sharing my experience with others in order to improve their expertise. I am also dedicated to personal and professional growth through diligent studying, discipline, and meaningful professional relationships. When not writing, I can be found playing hockey, practicing Brazilian Jiu-jitsu, watching the NJ Devils, reading, writing, or drawing. ~II Timothy 1:7~ Twitter: @justinmalbano

The Latest JavaScript Topics

article thumbnail
PWA on iOS, Part 5: Service Worker Updates, Cache, and Push
Service Workers on iOS wake in bursts and update on their own schedule. Learn safe updates, cache strategies, an offline queue and Web Push without surprises.
November 19, 2026
by Konstantin Shkurko
· 3,242 Views
article thumbnail
PWA on iOS, Part 4: What Add to Home Screen Really Does
Adding a PWA to the iPhone Home Screen creates a Web Clip with its own isolated storage. Learn what iOS saves, why logins disappear, and how to avoid costly bugs.
November 18, 2026
by Konstantin Shkurko
· 3,981 Views · 1 Like
article thumbnail
Detecting Duplicates With Machine Learning in 2026: From String Metrics to Embeddings and LLMs
Explore how machine learning uses string metrics, embeddings, and LLMs to detect duplicate records, documents, and code at scale.
November 12, 2026
by Ilya Dudkin DZone Core CORE
· 1,448 Views
article thumbnail
Building Enterprise Authentication With Angular, Spring Boot, SSO, and MFA
Implementing SSO and MFA for an enterprise Angular and Spring Boot platform taught me that authentication is frontend architecture, not a feature you bolt on at the end.
November 12, 2026
by Vaishnavi Khosla
· 1,185 Views
article thumbnail
Java to TypeScript in a Day: AI Migration Playbook
Learn from my journey using AI to build a TypeScript version of a Java in-memory database (Kiara DB), including the workflow and pitfalls to avoid.
November 4, 2026
by Anuj Kapoor
· 318 Views · 1 Like
article thumbnail
PWA on iOS, Part 3: Chrome on iPhone Is WebKit Too. How One Engine Sets the Rules for PWAs on iOS
Every iPhone browser runs on WebKit. PWA limits on iOS in practice: storage, sign-in, no install button, killed processes.
November 3, 2026
by Konstantin Shkurko
· 4,558 Views · 1 Like
article thumbnail
Guess the Speed: Building a Family Internet Speed Guessing Game
Learn how to build a multiplayer internet speed guessing game using TypeScript, Astro, Cloudflare Workers, Durable Objects, and WebSockets.
November 3, 2026
by NaveenKumar Namachivayam DZone Core CORE
· 1,233 Views · 1 Like
article thumbnail
PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
Why your PWA works on a laptop but not on an iPhone: HTTPS, the manifest, Service Worker lifecycle and the two caches that keep serving old code.
October 26, 2026
by Konstantin Shkurko
· 4,737 Views · 2 Likes
article thumbnail
PWA on iOS, Part 1: PWAs on the iPhone Are Older Than They Look
iPhone PWAs got full-screen mode in 2008, Service Workers in 2018, and push only in 2023. That slow, uneven history explains most of their quirks today.
October 20, 2026
by Konstantin Shkurko
· 3,360 Views · 2 Likes
article thumbnail
Builder Pattern + Faker in API Test Automation Using Playwright With TypeScript
Learn how to use the Builder Pattern with the Faker library in API Test automation with Playwright and TypeScript to generate dynamic test data.
October 13, 2026
by Faisal Khatri DZone Core CORE
· 2,315 Views
article thumbnail
How to Verify Response Data in API Testing With Playwright TypeScript
Learn how to verify the response data, including structure checks, basic validations, and more, in API Testing with Playwright TypeScript
September 25, 2026
by Faisal Khatri DZone Core CORE
· 2,385 Views · 1 Like
article thumbnail
When TypeScript Types Meet Untrusted AI: Building Type-Safe LLM Pipelines With Runtime Validation
Learn in this article how to treat LLM output as unknown until runtime schema validation proves it safe for typed application logic.
September 11, 2026
by Bhanu Sekhar Guttikonda DZone Core CORE
· 4,259 Views · 2 Likes
article thumbnail
Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
JSON hurts at scale. Protobuf cuts payload size by ~72%, reduces CPU overhead, and enforces typed contracts. However, it needs careful schema management.
September 11, 2026
by Bansidhar kadiya
· 4,353 Views · 3 Likes
article thumbnail
Angular Apps Don’t Need Another Chatbot: Building Agentic UI Workflows With TypeScript
Build agentic Angular UIs with typed events, Signals, explicit capabilities, human approval, and controlled rendering using AG-UI, A2UI, and WebMCP.
September 10, 2026
by Bhanu Sekhar Guttikonda DZone Core CORE
· 4,278 Views · 2 Likes
article thumbnail
How to Test GET API Requests With Playwright TypeScript
Learn how to test GET API requests using Playwright with TypeScript, including params, headers, timeouts, and status code validation.
September 10, 2026
by Faisal Khatri DZone Core CORE
· 3,893 Views · 5 Likes
article thumbnail
Fetching Information Randomly From JSON Using Node, Nuxt, Express
Nuxt.js, Node.js and Express code to filter out data based on user requirement and select data randomly from the filtered data.
September 10, 2026
by Richard Davis
· 4,417 Views · 2 Likes
article thumbnail
Node.js Microservices Architecture: A Complete Guide
This guide walks you through the core architecture components and design patterns needed to build scalable microservices with Node.js and explains when to use each.
September 2, 2026
by Megha Verma
· 4,612 Views · 3 Likes
article thumbnail
The Code-Volume Delusion: Rethinking Engineering Velocity in the AI Era
AI is shifting the engineering bottleneck downstream, requiring leaders to prioritize PR cycle times, CI/CD stability, and architectural health.
August 25, 2026
by Rupesh Dabbir
· 4,248 Views · 2 Likes
article thumbnail
Text Analysis Without a Backend: Replacing an LLM Call With Intl.Segmenter and 60 Lines of JavaScript
Build deterministic browser-based text tools instead of LLM APIs to reduce cost, latency, privacy risks, and nondeterministic results.
August 24, 2026
by Kevin Brown
· 3,699 Views · 1 Like
article thumbnail
Stop Hand-Rolling Chat UIs: Streaming LLM Tokens Into React Native Without the Jank
In a React Native chat, the keyboard and a streaming, resizing list fight over the scroll position and cause jank. KeyboardChatScrollView fixes it.
August 20, 2026
by Tammo Ronke
· 3,614 Views · 1 Like
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×