GCP Engineer: Menerapkan Lapisan Write-Behind Memcache untuk Mencegah Lonjakan Baca & Tulis di Cloud Datastore
Ketika ribuan perangkat IoT, aplikasi seluler, atau agen telemetri browser mengirimkan paket status setiap beberapa detik, membaca dan menulis langsung ke Google Cloud Datastore atau Firestore pada setiap paket akan dengan cepat menghabiskan batas penulisan entitas dan melipatgandakan tagihan bulanan Cloud Billing. Sebagai Google Cloud Platform (GCP) Engineer dan Backend Engineer, saya merancang lapisan penyangga write-behind dan read-through berbasis Memcache / Cloud Memorystore yang menyerap lebih dari 95% trafik telemetri berfrekuensi tinggi langsung di RAM.
1. Menggabungkan Paket Telemetri Berfrekuensi Tinggi dengan Increment Atomik
Alih-alih mengambil dan memperbarui entitas Cloud Datastore pada setiap ping telemetri yang masuk, kami menyimpan status perangkat terbaru dan menaikkan penghitung paket secara atomik di Memcache / Redis, serta hanya menulis agregat ke Cloud Datastore ketika jendela waktu berakhir atau terjadi perubahan status penting:
import time
from google.cloud import datastore
FLUSH_INTERVAL_SECONDS = 60
def ingest_device_telemetry(
cache_client: object,
ds_client: datastore.Client,
device_id: str,
cpu_pct: float,
status: str,
) -> str:
now = int(time.time())
state_key = f"telemetry:state:{device_id}"
last_flush_key = f"telemetry:last_flush:{device_id}"
cached_state = cache_client.get(state_key) or {}
prev_status = cached_state.get("status")
packet_count = cache_client.incr(f"telemetry:Count:{device_id}", 1, initial_value=1)
new_state = {
"device_id": device_id,
"cpu_pct": cpu_pct,
"status": status,
"packet_count": packet_count,
"updated_at": now,
}
cache_client.set(state_key, new_state, time=3600)
last_flush = int(cache_client.get(last_flush_key) or 0)
status_changed = prev_status is not None and prev_status != status
# Hanya simpan ke Cloud Datastore saat terjadi transisi status atau setiap 60 detik
if status_changed or (now - last_flush) >= FLUSH_INTERVAL_SECONDS:
if cache_client.add(f"telemetry:flush_lock:{device_id}", "1", time=10):
key = ds_client.key("DeviceTelemetrySummary", device_id)
entity = datastore.Entity(key=key)
entity.update(new_state)
ds_client.put(entity)
cache_client.set(last_flush_key, now, time=3600)
return "FLUSHED_TO_DATASTORE"
return "BUFFERED_IN_MEMCACHE"
2. Mencegah Cache Stampede pada Kueri Dashboard
Penggunaan kunci mutex atomik cache_client.add(...) memastikan bahwa apabila 20 paket telemetri tiba pada milidetik yang sama setelah jendela 60 detik berakhir, hanya satu worker yang menulis ke Cloud Datastore sementara 19 worker lainnya selesai seketika. Padukan arsitektur ini dengan Pencatat Penggunaan Heartbeat di Cloud Datastore serta Testbed Lokal Datastore & Memcache Hermetik. Kunjungi Layanan Sprint Teknik 1 Hari untuk optimasi biaya GCP Anda.