Microservices & Scaling

Preview — 3 of 10 questions

What problem does this pipeline have?

javascript
const fs = require("fs");
const { Transform } = require("stream");

const input = fs.createReadStream("large-file.txt");

// Custom transform: uppercase
const uppercase = new Transform({
  transform(chunk, encoding, callback) {
    this.push(chunk.toString().toUpperCase());
    callback();
  }
});

const output = fs.createWriteStream("output.txt");

input.pipe(uppercase).pipe(output);
ANo problem; code is correct.
BNo backpressure handling; might cause memory issues.
CStreams are deprecated.
DOnly works for small files.

When should you use Worker Threads vs Child Processes?

javascript
const { Worker } = require("worker_threads");

const worker = new Worker("./calculation.js");

worker.on("message", (result) => {
  console.log("Result:", result);
});

worker.postMessage({ data: 1000000000 });
AWorker Threads for everything.
BChild Processes: CPU-heavy tasks, isolate failures. Worker Threads: CPU-heavy tasks, shared memory.
CChild Processes only for file I/O.
DNo difference between them.

What advanced error recovery patterns exist?

javascript
class CircuitBreaker {
  constructor(fn, options = {}) {
    this.fn = fn;
    this.failures = 0;
    this.threshold = options.threshold || 5;
    this.timeout = options.timeout || 60000;
    this.state = "CLOSED"; // CLOSED, OPEN, HALF_OPEN
  }
  
  async execute(...args) {
    if (this.state === "OPEN") {
      if (Date.now() - this.openedAt > this.timeout) {
        this.state = "HALF_OPEN";
      } else {
        throw new Error("Circuit breaker is OPEN");
      }
    }
    
    try {
      const result = await this.fn(...args);
      this.onSuccess();
      return result;
    } catch (error) {
      this.onFailure();
      throw error;
    }
  }
  
  onSuccess() {
    this.failures = 0;
    this.state = "CLOSED";
  }
  
  onFailure() {
    this.failures++;
    if (this.failures >= this.threshold) {
      this.state = "OPEN";
      this.openedAt = Date.now();
    }
  }
}

const apiCall = new CircuitBreaker(
  () => fetch("https://api.example.com/data"),
  { threshold: 5, timeout: 60000 }
);

app.get("/data", async (req, res) => {
  try {
    const data = await apiCall.execute();
    res.json(data);
  } catch (error) {
    res.status(503).json({ error: "Service unavailable" });
  }
});
AJust log errors and continue.
BCircuit breaker, retry with exponential backoff, graceful degradation.
CErrors should never happen.
DRestart entire application.

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.