Problems with Time-Based Code & How Fake Clocks Solve Them
⚠️ Problems with Time-Based Code in Tests When writing Go programs, we often rely on time-related functions like: time.After time.NewTicker time.NewTimer time.Sleep These are useful for implementing timeouts, periodic tasks, and scheduled operations. However, they introduce several problems in tests: 1️⃣ Tests Become Slow If a function waits 10 seconds before timing out, your test also takes 10 seconds. This slows down CI/CD pipelines and developer productivity. 2️⃣ Flaky Tests (Intermittent Failures) Real-world execution times fluctuate due to CPU load, network latency, and system clock drift. Example: A timeout-based test might pass on a fast machine but fail on a slow one. 3️⃣ No Control Over Time You can’t fast-forward time or pause execution. Makes it hard to simulate timeouts, retries, and delays. 4️⃣ Hard to Test Race Conditions Go routines using real time can interleave unpredictably, leading to non-deterministic tests. ✅ Solution: Using Fake Clocks in Go To solve these problems, we use a fake clock instead of the real time package. Fake clocks allow us to: ✅ Fast-forward time instead of waiting in real-time. ✅ Ensure predictable timing behavior in tests. ✅ Make tests run instantly, improving speed. ✅ Simulate timeouts, delays, and retries deterministically.

⚠️ Problems with Time-Based Code in Tests
When writing Go programs, we often rely on time-related functions like:
time.After
time.NewTicker
time.NewTimer
time.Sleep
These are useful for implementing timeouts, periodic tasks, and scheduled operations. However, they introduce several problems in tests:
1️⃣ Tests Become Slow
- If a function waits 10 seconds before timing out, your test also takes 10 seconds.
- This slows down CI/CD pipelines and developer productivity.
2️⃣ Flaky Tests (Intermittent Failures)
- Real-world execution times fluctuate due to CPU load, network latency, and system clock drift.
- Example: A timeout-based test might pass on a fast machine but fail on a slow one.
3️⃣ No Control Over Time
- You can’t fast-forward time or pause execution.
- Makes it hard to simulate timeouts, retries, and delays.
4️⃣ Hard to Test Race Conditions
- Go routines using real time can interleave unpredictably, leading to non-deterministic tests.
✅ Solution: Using Fake Clocks in Go
To solve these problems, we use a fake clock instead of the real time
package. Fake clocks allow us to:
✅ Fast-forward time instead of waiting in real-time.
✅ Ensure predictable timing behavior in tests.
✅ Make tests run instantly, improving speed.
✅ Simulate timeouts, delays, and retries deterministically.