← Kembali

Retry Logic Strengthening — ALL Exceptions & Health Monitor 5 Fixes

fetcher monitoring reliability retry

errors

  • Fetcher gagal di network errors — fetch_single_ticker() hanya retry untuk rate limit errors (HTTP 429). Network timeout, connection refused, DNS resolution failure, SSL handshake error tidak di-handle. Akibatnya: saham-saham tertentu sering ke-skip tanpa sempat di-retry.

Actual log lines: 2026-06-25 19:17:32 - __main__ - WARNING - 50 consecutive failures — rate limited. Pausing 120s... 2026-06-25 19:37:03 - __main__ - WARNING - 50 consecutive failures — rate limited. Pausing 120s... 2026-06-27 10:48:36 - __main__ - INFO - Failed: 1667 2026-07-30 03:30:01 - __main__ - INFO - RETRY PHASE: Re-processing 40 failed symbols... Retry phase done: Success=0, Failed=40

  • Coverage rendah — Setiap batch, ada ~5-15 stocks yang gagal karena network glitch. Nggak ada mekanisme untuk coba lagi di akhir loop. Error ini akumulasi tiap hari, makin banyak data yang missing.
  • Data health monitor false alarm — Monitor yang baru dibuat (2026-06-17) sering trigger alarm palsu:
  • Cron error: #!/usr/bin/python nggak portable — beda server beda path Python
  • Server offline sesaat dianggap data stale — nggak ada pengecekan internet connectivity
  • Langsung ambil kesimpulan pas pertama kali error — nggak ada retry
  • Nggak deteksi process yang jalan via PM2 — cuma pgrep yang bisa miss
  • Threshold 100% untuk 1h dan 1d nggak realistis — coverage saham tidur jauh di bawah itu

context

Fetcher batch jalan tiap jam lewat PM2 cron (sniper-fetcher). Network ke Yahoo Finance tidak selalu stabil — kadang timeout, kadang koneksi dropped. Data health monitor (created 2026-06-17) adalah script baru yang belum production-tested. Monitoring berteriak tiap jam karena coverage saham tidur rendah, padahal itu normal.

problem

Dua masalah paralel: (1) retry logic fetcher terlalu lemah — cuma handle satu jenis error (rate limit), padahal network errors lebih sering terjadi di production. (2) Data health monitor yang dibikin untuk solusi malah jadi masalah baru — 5 bugs bikin false alarm terus, jadi percuma. Keduanya butuh strengthening.

investigation

  • Retry logic: baca kode fetch_single_ticker() di fetcher_batch.py. Ketahuan: exception handler cuma catch ratelimit.RateLimitException. Error lain kayak requests.ConnectionError, requests.Timeout, socket.gaierror (DNS fail) nggak di-catch. Juga: setelah semua stocks di-loop, nggak ada phase untuk coba lagi stocks yang gagal.

Original retry code (before fix): python # ❌ SEBELUM — retry CUMAN untuk rate limit: except Exception as e: err_str = str(e).lower() is_rate_limit = 'rate limit' in err_str or 'too many requests' in err_str if is_rate_limit: time.sleep(wait) return self.fetch_single_ticker(...) # retry ONLY rate limit # Kalau network error / timeout / connection error → langsung give up return pd.DataFrame() # ❌ tidak ada retry!

  • Health monitor bugs: review data_health_monitor.py baris per baris:
  • Shebang hardcoded #!/usr/bin/python — di beberapa server Python ada di /usr/bin/python3
  • Langsung query DB tanpa cek koneksi internet — kalau server mati internet, data kelihatan stale padahal nggak
  • Single attempt — kalau query timeout atau DB busy, langsung trigger alarm
  • pgrep fetcher — nggak mendeteksi process yang jalan sebagai PM2 service dengan nama beda
  • Threshold coverage_threshold = 1.0 (100%) — coverage saham tidur rata-rata cuma 30-50%

root-cause

  1. Retry logic lemah — developer cuma mikirin rate limiting (yang emang umum di Yahoo Finance), tapi lupa network errors lain yang lebih frequent di production environment dengan koneksi tidak stabil.

python # 1. Retry handler hanya mengecek 'rate limit' string di error message. # Network timeout/ConnectionError/DNS failure tidak di-handle.

  1. Batch retry phase tidak ada — alurnya: fetch semua → selesai. Nggak ada loop kedua buat stocks yang gagal.

python # 2. Tidak ada retry batch — stocks yang gagal di batch 1-20 # tidak pernah dicoba ulang (langsung dianggap failed total).

  1. 5 bugs di health monitor — semuanya karena lack of production testing: shebang nggak portable, missing internet check, no retry mechanism, incomplete process detection, dan threshold idealis (100%) yang nggak match realita coverage saham tidur.

python # 3. shebang #!/usr/bin/python tidak portable — di server path python bisa berbeda.

solution

  1. Retry ALL exceptions di fetch_single_ticker() — ganti catch spesifik jadi except Exception as e. Tambah retry counter dengan exponential backoff (3× percobaan, delay 5s → 10s → 20s).

Fixed retry logic: python # ✅ SESUDAH — retry untuk SEMUA exception (3x percobaan): except Exception as e: if attempt < 3: logger.warning(f"Fetch error for {yf_symbol} (attempt {attempt}): {e}") logger.info(f" Retrying {yf_symbol} in {wait}s...") time.sleep(wait) return self.fetch_single_ticker(yf_symbol, period, interval, attempt + 1) else: logger.warning(f"Fetch error for {yf_symbol} (attempt {attempt}/3, giving up): {e}")

  1. Batch retry phase — di akhir main() loop, kumpulin semua stock_id yang gagal. Loop lagi dengan retry terbatas (2×). Ini nangkep kasus network glitch temporal.
  2. Data health monitor 5 fixes:
  3. Shebang: #!/usr/bin/env python → ganti jadi #!/usr/bin/env python... wait, better: pake sys.executable untuk subprocess calls
  4. Internet check: ping 8.8.8.8 -c 1 -W 5 sebelum cek data. Kalau gagal, skip siklus.

    python # data_health_monitor.py — internet check dulu sebelum fetch import subprocess def internet_available(): result = subprocess.run(['ping', '-c', '1', '8.8.8.8'], capture_output=True, timeout=5) return result.returncode == 0

  5. Exponential backoff: 3× percobaan dengan delay 10s → 30s → 60s

  6. PM2 detection: pm2 pid sniper-fetcher di samping pgrep. Gabung hasil keduanya.
  7. Threshold realistis: 1d → 50%, 1h → 30%. Ini berdasarkan distribusi coverage aktual.

insight

  • Defensive programming itu penting. Exception handling jangan cuma untuk error yang kamu tau — handle Exception secara general, lalu specific error sebagai tambahan. Network errors itu unpredictable.
  • Retry strategy harus multi-level. Retry di level function (per stock) DAN retry di level batch (failed stocks di akhir). Dua mekanisme yang tackle problem berbeda: (a) transient error pas fetch, (b) systemic error yang selesai dalam beberapa menit.
  • Threshold ideal vs realita. Setting threshold monitoring berdasarkan asumsi (100% coverage) itu naif. Selalu ukur dulu data aktual, lalu set threshold berdasarkan distribusi real. Coverage saham tidur 30-50% itu wajar.
  • False alarm = no alarm. Kalau monitoring terlalu sering teriak palsu, orang bakal ignore. Lebih baik threshold longgar tapi akurat, daripada ketat tapi banyak false positive.

gotchas

  • except Exception itu catch ALL — termasuk KeyboardInterrupt dan SystemExit kalau nggak hati-hati. Better: except (requests.ConnectionError, requests.Timeout, socket.gaierror, ...) atau tambah except KeyboardInterrupt: raise di awal.
  • Exponential backoff: jangan lupa max delay. Kalau nggak dibatasin, retry ke-10 delay-nya bisa berjam-jam. Set max 60-120 detik.
  • Ping check (ping 8.8.8.8) bisa gagal kalau server block ICMP. Alternatif: curl -s --max-time 5 https://google.com atau socket.connect(('8.8.8.8', 53)).
  • PM2 process name di pm2 pid harus match persis dengan nama di ecosystem.config.js. Case-sensitive. Cek dengan pm2 list dulu.
  • Threshold monitoring: jangan set terlalu rendah juga — nanti data beneran stale nggak ketahuan. 50% untuk 1d itu reasonable karena saham tidur emang nggak selalu punya data harian.
  • Retry phase untuk failed stocks: pastikan total execution time nggak exceed cron interval. Cron tiap jam, batch retry jangan sampe 30 menit.

Terakhir diperbarui 31 Jul 2026 00:15

Comments