Privacy‑Preserving Browser‑Based Federated Learning with TensorFlow.js and Web Workers

Mahmut Sarıkaya 4 min read 1 Views 0
Privacy‑Preserving Browser‑Based Federated Learning with TensorFlow.js and Web Workers

Why Browser‑Based Federated Learning Matters

Imagine a web app that can improve its recommendations without ever sending raw user data to a central server. In 2023, more than 70% of internet traffic originated from browsers, yet only a fraction of AI models run locally. Bringing federated learning to the browser closes that gap, turning every visitor into a contributing node while keeping personal information on the device.

Core Concepts: Federated Learning and Privacy

Federated learning splits the traditional training pipeline into three steps: local model update, secure aggregation, and global model broadcast. The key privacy claim is that raw samples never leave the client. When combined with differential privacy noise or secure multiparty computation, the approach satisfies regulations such as GDPR and CCPA while still delivering a model that benefits from millions of edge updates.

Setting Up TensorFlow.js in the Browser

TensorFlow.js provides the same high‑level API as its Python counterpart, but it runs on WebGL or the CPU. To start, include the library via a CDN and create a tiny convolutional network that classifies handwritten digits. The following snippet demonstrates a minimal model definition:


const model = tf.sequential();
model.add(tf.layers.conv2d({filters:8,kernelSize:3,activation:'relu',inputShape:[28,28,1]}));
model.add(tf.layers.maxPooling2d({poolSize:2}));
model.add(tf.layers.flatten());
model.add(tf.layers.dense({units:10,activation:'softmax'}));
model.compile({optimizer:'adam',loss:'categoricalCrossentropy',metrics:['accuracy']});

Because the script runs on the main thread, heavy tensor operations could freeze the UI. That is where Web Workers become essential.

Offloading Computation with Web Workers

Web Workers provide a separate JavaScript execution context that shares memory only through structured cloning. By loading TensorFlow.js inside a worker, the UI stays responsive while the model trains on the client’s data. Create a file worker.js and import the library with importScripts:

// worker.js
importScripts('https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.12.0');
self.onmessage = async function(e){
  const {type, payload} = e.data;
  if(type === 'train'){ 
    const {xs, ys, epochs} = payload;
    await model.fit(xs, ys, {epochs});
    const weights = await model.getWeights().map(w=>w.array());
    self.postMessage({type:'update', payload:weights});
  }
};

In the main script, spawn the worker, transfer the data, and listen for the updated weight array. This pattern isolates heavy linear algebra from the UI thread.

Implementing a Simple Federated Round

A federated round consists of three phases: (1) the server sends the current global model, (2) each client trains locally for a few epochs, and (3) the server aggregates the received updates. In a pure‑browser demo, the “server” can be a lightweight Node.js endpoint or even a Firebase function. The client code below shows how to fetch the global weights, feed them into the worker, and post the result back:

async function startRound(){
  const resp = await fetch('/global-weights');
  const globalWeights = await resp.json();
  const weightTensors = globalWeights.map(w=>tf.tensor(w));
  model.setWeights(weightTensors);
  const xs = tf.browser.fromPixels(document.getElementById('sample')).reshape([1,28,28,1]).div(255);
  const ys = tf.oneHot(tf.tensor1d([3],'int32'),10);
  worker.postMessage({type:'train', payload:{xs,ys,epochs:2}});
}
worker.onmessage = e=>{
  if(e.data.type==='update'){
    fetch('/upload-weights',{
      method:'POST',
      headers:{'Content-Type':'application/json'},
      body:JSON.stringify(e.data.payload)
    });
  }
};
startRound();

Notice that tensors are transferred via the structured clone algorithm; large buffers are moved efficiently without copying.

Handling Model Aggregation Securely

To preserve privacy, the server should not simply average raw weight values. Adding Gaussian noise calibrated to a target epsilon (e.g., ε=1.0) satisfies differential privacy. A practical approach is to compute the sum of all client updates, then inject noise before dividing by the number of participants. The server can also employ Secure Aggregation protocols that use additive secret sharing, but implementing them in JavaScript is non‑trivial and often outsourced to specialized libraries.

Performance Tips and Pitfalls

1. Use tf.tidy inside workers to release intermediate tensors and avoid memory leaks. 2. Prefer WebGL backend for convolutional layers; benchmark with tf.ENV.get('WEBGL_RENDER_BACKEND'). 3. Limit each client to 1–3 epochs and a small batch size (e.g., 32) to keep training time under 5 seconds on a typical laptop. 4. Test on low‑end devices; Safari on iOS may fall back to the CPU, increasing latency dramatically.

Conclusion

By combining TensorFlow.js, Web Workers, and a disciplined federated learning loop, developers can deliver privacy‑preserving AI directly inside the browser. The architecture keeps raw data on the client, leverages native GPU acceleration, and scales to millions of users without a heavyweight backend. As browsers continue to expose more compute capabilities, this pattern will become a cornerstone for responsible, edge‑first machine learning.

Sources

  • TensorFlow.js Official Documentation
  • Google AI Blog – Federated Learning at Scale
  • MDN Web Docs – Using Web Workers

Author: Mahmut Sarıkaya — sarikayadev.com

Tags: #federated learning #TensorFlow.js #Web Workers #privacy preserving AI #browser AI
Share:
M

Written by

Mahmut Sarıkaya

Software Developer

Comments

No comments yet. Be the first to share your thoughts!

Leave a Comment

8 + 5 =