Skip to Content
Course content

45: Working with Time and Durations

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this mistake in almost every codebase I've inherited from developers moving to Go from languages like Python or JavaScript. They treat time as a raw number—usually an integer—and pass it around the application. It seems intuitive at first, but it's a recipe for a production outage that's incredibly frustrating to debug.

The ambiguity of raw integers

Imagine you're building a simple cache for a user session. You want to specify how long a session remains valid. A naive implementation might look like this:

func CreateSession(userID string, timeout int) {
    // Assume we store this in Redis or a map
    fmt.Printf("Session created for %s, expires in %d\n", userID, timeout)
}

// Calling the function
CreateSession("user_123", 30) 

On the surface, this works. But here is where the friction starts: what does 30 actually mean? If you're the one who wrote the function, you know it's seconds. But six months from now, or for a new teammate, it's a guessing game. Is it milliseconds? Seconds? Minutes? I've spent hours debugging "ghost" bugs where one developer passed 30 meaning seconds, but the receiving function interpreted it as milliseconds, causing sessions to expire in 0.03 seconds.

When you use raw integers, you're relying on documentation or naming conventions (like timeoutSeconds) to enforce correctness. In a large project, that's a fragile strategy. You're essentially asking your teammates to keep a mental map of units for every single function call.

Letting the type system handle the units

In Go, we have time.Duration. It's not a complex object; it's actually just an int64 under the hood representing nanoseconds. However, because it's a distinct type, it allows us to be explicit. I always tell my juniors: if a function accepts a duration of time, it should never take an int.

Here is how we do this properly:

func CreateSession(userID string, timeout time.Duration) {
    fmt.Printf("Session created for %s, expires in %v\n", userID, timeout)
}

// Now the call site is crystal clear
CreateSession("user_123", 30 * time.Second)
CreateSession("user_456", 5 * time.Minute) 

By using time.Duration, the unit is baked into the call. You can't accidentally pass "30" and hope for the best because 30 is an untyped constant that won't automatically satisfy a time.Duration parameter in many contexts, and even when it does, 30 as a duration is 30 nanoseconds—which is so obviously wrong that it usually triggers a red flag during testing.

Where the logic actually breaks

The real danger happens when you start doing math with time. If you use integers, you're doing basic arithmetic. But if you use time.Time and time.Duration, you get access to methods that handle the edge cases for you. For example, if you want to check if a session has expired, you might be tempted to subtract two timestamps and compare the result to an integer.

Instead, use time.Since(). It's a convenience wrapper that reads like a sentence and prevents you from having to manually call time.Now().Sub(startTime) every single time. I find that the more I can move my time logic toward "readable prose" and away from "integer subtraction," the fewer bugs I ship.

One final tip: be careful when multiplying durations by variables. If you have a variable retryCount := 3 and you want to wait retryCount * time.Second, Go handles this fine because the constant time.Second promotes the expression to a duration. But if you're dealing with an integer variable from a config file, you'll need to cast it: time.Duration(configValue) * time.Second. It's a small bit of verbosity, but it's a fair price to pay for knowing exactly how many seconds your application is actually sleeping.




📋 Practical Task

Refactoring the Request Timeout Guard

You have been handed a piece of legacy code for a network proxy. The current implementation uses raw integers for timeouts, which has caused several "instant timeout" bugs because some developers are passing milliseconds while others pass seconds.

Your Task: Refactor the following code to use time.Duration instead of int. Ensure that the FetchData function is called with a duration of 5 seconds, and the WaitForRetry function is called with 2 seconds.

package main

import (
	"fmt"
	"time"
)

// TODO: Refactor this to use time.Duration
func FetchData(url string, timeout int) {
	fmt.Printf("Fetching %s with a timeout of %d\n", url, timeout)
}

// TODO: Refactor this to use time.Duration
func WaitForRetry(attempts int, delay int) {
	fmt.Printf("Retrying %d times with a delay of %d\n", attempts, delay)
}

func main() {
	// These calls are currently ambiguous. Fix them.
	FetchData("https://api.example.com", 5) 
	WaitForRetry(3, 2)
}
Rating
0 0

There are no comments for now.

to be the first to leave a comment.