跳到正文
DEV Community· Ziad Taha·· 3 小時前AI 評分48

為 FaceMark 人臉識別 API 編寫熔斷器及 Bitcask 式 WAL 引擎(附實際程式碼)

I Wrote a Circuit Breaker and a Bitcask-Style WAL Engine for My Face Recognition API (With Real Code)

AI 導讀

FaceMark 人臉識別 API 的開發者自行以 NestJS 和 TypeScript 編寫熔斷器,並以 Python 實作 Bitcask 式 WAL 引擎,應對 AI 服務故障及人臉嵌入資料遺失。熔斷器在連續失敗 3 次後開啟,15 秒後以單一探測請求測試服務;WAL 則採用只追加寫入及 CRC32 校驗,並在啟動時重播記錄以恢復索引和快取。

正文

A few weeks ago I shared what I learned building FaceMark, my facial-recognition attendance system (NestJS + Angular + a Python AI service). This post is the technical deep-dive I promised myself I'd write: the two components I built from scratch instead of pulling in a library, why I built them, and how they actually work.

Everything below is running code from the repo: ZiadtahaM/FaceMark.

Why build these myself?

Two reasons. First, both failure modes bit me in real testing: the AI service hanging froze my entire API, and restarting the Python service lost face embeddings stored as a pickle file that had corrupted once already. Second, I'm a junior developer, and I wanted to understand the patterns, not just import them. Both designs are straight out of Designing Data-Intensive Applications (Kleppmann) - the circuit breaker from the reliability chapters and the storage engine from Chapter 3's Bitcask model.

Component 1: The circuit breaker (TypeScript, NestJS)

VisionService calls the FastAPI service over HTTP for every face registration and recognition. When FastAPI hangs (TensorFlow is loading, or it just died), each hanging request holds a thread. Enough of them and the whole API is unresponsive - a cascade failure caused by one dependency.

The breaker has three states:

export enum CircuitState {
  CLOSED = 'CLOSED',
  OPEN = 'OPEN',
  HALF_OPEN = 'HALF_OPEN',
}

The execute wrapper does four things: evaluates whether it's time to probe again, fast-fails while OPEN, caps every call with a timeout budget via Promise.race, and records the outcome:

public async execute<T>(action: () => Promise<T>, fallback?: () => Promise<T> | T): Promise<T> {
  this.evaluateState();

  if (this.state === CircuitState.OPEN) {
    this.logger.warn(`[${this.serviceName}] Fast-failing: Circuit is OPEN.`);
    if (fallback) {
      return fallback();
    }
    throw new ServiceUnavailableException(
      `[${this.serviceName}] Service is temporarily unavailable due to upstream instability. Circuit is OPEN.`
    );
  }

  try {
    // Enforce timeout budget capping
    const result = await Promise.race([
      action(),
      new Promise<never>((_, reject) =>
        setTimeout(
          () => reject(new Error(`[${this.serviceName}] Request timed out after ${this.timeoutMs}ms`)),
          this.timeoutMs
        )
      ),
    ]);

    this.onSuccess();
    return result;
  } catch (error) {
    this.onFailure(error);
    if (fallback) {
      return fallback();
    }
    throw error;
  }
}

State transitions are driven by counters, not timers:

private onFailure(error: any): void {
  this.failureCount++;

  if (this.state === CircuitState.HALF_OPEN || this.failureCount >= this.failureThreshold) {
    this.state = CircuitState.OPEN;
    this.lastStateChange = Date.now();
  }
}

Three consecutive failures trip CLOSED to OPEN. OPEN rejects immediately with a 503 for 15 seconds, then a single canary request probes the service in HALF_OPEN. If the canary succeeds, failureCount resets and the circuit closes; if it fails, it re-opens instantly (that's the HALF_OPEN || condition - one failed probe is enough to re-open).

For retries I use exponential backoff with full jitter (the AWS Architecture Blog variant):

/**
 * Exponential backoff with full jitter formula:
 * t = random(0, min(maxBackoffMs, baseMs * 2^attempt))
 */
public static calculateJitterBackoff(attempt: number, baseMs = 500, maxBackoffMs = 8000): number {
  const exponential = Math.min(maxBackoffMs, baseMs * Math.pow(2, attempt));
  return Math.floor(Math.random() * exponential);
}

Full jitter matters because without it, N clients retrying after a failure all wake up at the same computed times and hit the recovering service in synchronized waves. Randomizing across [0, exponential] spreads the load.

What it fixed: with the AI service killed, the API kept serving auth, courses, and attendance normally, and recognition endpoints returned instant 503s instead of hanging for 15+ seconds each. Before the breaker, killing FastAPI took the whole API down within about a minute of real traffic.

Component 2: A Bitcask-style WAL for face embeddings (Python)

Face embeddings (512-dim vectors from DeepFace/FaceNet512) live in the Python service. My first version pickled a dict to disk. It worked until the process died mid-write and I lost every enrolled face.

So I wrote BitcaskWalEngine, a log-structured append-only store. Every record on disk looks like this:

[CRC32: 4B][Timestamp: 8B][Tombstone: 1B][KeyLen: 2B][ValLen: 4B][Key][Value]
# 4 (CRC32) + 8 (Timestamp float) + 1 (Tombstone flag) + 2 (KeyLen) + 4 (ValLen) = 19 bytes
HEADER_FORMAT = "!IdBHI"
HEADER_SIZE = struct.calcsize(HEADER_FORMAT)

The design has four moving parts:

  1. Writes are appends only. A put serializes the embedding, computes a CRC32 over header + key + value, appends the record, fsyncs, then updates the in-memory index. No in-place updates, ever. The last record for a key wins.
  2. An in-memory Keydir maps each key to (offset, size, timestamp) in the log, so reads are one seek, not a scan. A second in-memory cache holds the vectors themselves for fast similarity search.
  3. Crash recovery is a sequential replay. On startup the engine scans the log front to back, verifying the CRC32 of every record. A record that fails its CRC (that's the torn write from a mid-write crash) is counted as corrupt and skipped - everything before it survives:
def _recover(self):
    """Crash-recovery: Rebuilds Keydir and memory cache by scanning WAL sequentially."""
    self._file.seek(0)
    valid_records = 0
    corrupt_records = 0

    while True:
        offset = self._file.tell()
        header_bytes = self._file.read(self.HEADER_SIZE)
        if not header_bytes or len(header_bytes) < self.HEADER_SIZE:
            break

        crc, ts, tombstone, k_len, v_len = struct.unpack(self.HEADER_FORMAT, header_bytes)
        # ... verify CRC, rebuild keydir and cache
  1. Compaction and tombstones. Deletes write a record with the tombstone flag set rather than removing bytes. A garbage-collection pass eventually rewrites the log keeping only live records, which is how the file stays bounded despite being append-only.

There was also a pragmatic piece I enjoyed: the engine auto-migrates the old pickle file into WAL format on first run, so existing deployments upgraded without a manual step:

if not os.path.exists(self.wal_path) and self.legacy_pickle_path and os.path.exists(self.legacy_pickle_path):
    self._migrate_legacy_pickle()

What it fixed: I've since killed the AI service mid-write on purpose, repeatedly. Every time, recovery comes back with all valid records and a count of the corrupt tail it skipped. The pickle version failed this test the first time.

What I'd tell another junior dev

  • Write the pattern once by hand, then use the library. I now deeply understand what Resilience4j/Polly-style breakers and real LSM-tree storage engines do, because I felt the edge cases myself: the HALF_OPEN re-trip, the torn write, the replay ordering.
  • Design for the failure you already observed. I didn't add a circuit breaker because it sounded enterprise-grade. I added it because my API hung and I could reproduce it.
  • CRCs and fsync are the whole point. A WAL without integrity checks is just a file you append to and hope.

Honest caveat: neither component is production-grade. SQLite would replace my WAL with one dependency, and there are mature breaker libraries for NestJS. But as a learning exercise that also made the system genuinely more robust, I'd do it again.


I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) based in Alexandria, Egypt, currently open to junior roles and freelance work. If you're hiring, or you spotted something in my code you'd have done differently, I want to hear it:

來源:DEV Community · dev.to