FOUNDING PRICING · 40% OFFfor the first 1,000 members · from ₹95/month
OutageCloudflare11 min read

Cloudflare's 2017 Leap Second Bug: When Time Went Backwards

How the leap second on 1 January 2017 made a Go program at Cloudflare measure negative time and fail DNS lookups, and why wall clocks differ from monotonic.

ShareXLinkedInWhatsApp
A large red LED time display labelled USNO Master Clock at the entrance to the U.S. Naval Observatory in Washington, D.C.
A large red LED time display labelled USNO Master Clock at the entrance to the U.S. Naval Observatory in Washington, D.C. Photo: Tony Webster, CC BY 2.0, via Wikimedia Commons.

At midnight UTC on 1 January 2017, the world's clocks inserted one extra second. Inside Cloudflare's DNS server, a subtraction of two timestamps that could "never" be negative came out negative, a random-number function refused the result, and some DNS lookups began to fail. The disruption was small in percentage terms, but it lasted for hours and it came from an assumption almost every programmer makes: that time only moves forwards.

This post explains what a leap second is, why a computer has two different clocks, and how one line of ordinary-looking code turned a one-second adjustment into failed lookups.

A diagram of the failure chain at Cloudflare: the wall clock steps back one second at the leap second, a round-trip time computed by subtracting two wall clock readings becomes negative, the smoothed value turns negative, rand.Int63n panics on the negative argument, and the DNS lookup for a CNAME record fails.

What broke for users

Cloudflare runs its own authoritative DNS server, written in Go, which it calls RRDNS. When the leap second arrived, RRDNS on some machines started hitting a panic, Go's term for a runtime error that aborts the current work. The panics were caught by Go's recover mechanism, so the servers did not crash outright, but the lookups being processed at that moment were not answered.

Cloudflare's own numbers describe the scale:

  • Only customers using CNAME records with Cloudflare were affected.
  • A small number of machines across its 102 data centres at the time were hit.
  • At the peak, about 0.2% of DNS queries to Cloudflare failed.
  • Under 1% of all HTTP requests to Cloudflare saw an error.

Those are small fractions of a very large number. A site whose name cannot be resolved is simply unreachable for that visitor.

The timeline

All times are UTC on 1 January 2017, as published by Cloudflare.

TimeWhat happened
00:00The leap second occurs. Impact starts.
00:10The problem is escalated to engineers.
00:34The issue is confirmed.
00:55A mitigation is deployed to one canary machine and confirmed.
01:03The mitigation is deployed to one canary data centre and confirmed.
01:23The fix is deployed in the most affected data centre.
01:45The fix is being deployed to major data centres.
01:48The fix is being deployed everywhere.
02:50The fix has reached the most affected data centres.
06:45Impact ends.

The problem was escalated ten minutes into New Year's Day and confirmed within about half an hour. Even under that pressure the fix went out in careful stages: one machine, one data centre, then the rest.

What a leap second is

There are two ways to define a day. One is astronomical: one rotation of the Earth. The other is atomic: 86,400 seconds, where a second is defined by caesium atoms. The two do not agree exactly, because the Earth's rotation is slightly irregular and is slowing over the long term.

Civil time, UTC, ticks at the atomic rate. To stop it drifting away from the Sun, UTC is kept within 0.9 seconds of the astronomical time scale called UT1. When the gap grows, a body called the International Earth Rotation and Reference Systems Service (IERS) announces a leap second, about six months ahead. On the chosen day the last minute has 61 seconds.

The announcement for this one, Bulletin C 52, was issued on 6 July 2016. It gave the exact sequence of second labels:

2016-12-31 23:59:59
2016-12-31 23:59:60   <- the leap second
2017-01-01 00:00:00

Leap seconds began in 1972, and this was the 27th.

A long polished metal cylinder with optical equipment mounted on a white cabinet labelled NIST-7, in a laboratory room.
NIST-7, a caesium atomic clock unveiled in 1993 at the US National Institute of Standards and Technology. Clocks of this kind define the atomic second that UTC ticks in. Photo: National Institute of Standards and Technology, Public domain, via Wikimedia Commons.

Why computers handle it badly

Most systems store time as a count of seconds since 1 January 1970, known as Unix time, and assume every day has exactly 86,400 seconds. There is no number in that scheme for 23:59:60. The Linux manual says it directly: the system's real-time clock counts seconds since the epoch and ignores leap seconds.

So something has to give. The common approach, described in the Go team's design document on this topic, is that the clock is reset so that a second is repeated: the counter reaches the end of 23:59:59, then steps back and counts that second again. From a program's point of view, the clock briefly runs backwards.

Some large operators avoid the step with a "leap smear", running their clocks very slightly slow for many hours so that the extra second is absorbed gradually. That keeps time moving forwards, at the cost of being a fraction of a second away from true UTC during the smear.

Two clocks: wall and monotonic

An operating system offers a program more than one clock, because "what time is it?" and "how long did that take?" are different questions.

The wall clock answers the first. On Linux it is CLOCK_REALTIME. It tries to match UTC, so it can be changed: by an administrator, by the NTP service that synchronises it over the network, or by a leap second. It can jump forwards or backwards.

The monotonic clock answers the second. On Linux it is CLOCK_MONOTONIC. Its value on its own means nothing (on Linux it counts from system boot), but it is not affected by jumps in the system time, and consecutive readings never go backwards. It is a stopwatch.

Wall clockMonotonic clock
Question it answersWhat time is it?How much time has passed?
Can be set or steppedYesNo
Can go backwardsYesNo
Comparable across machinesRoughly, if synchronisedNo
Use it forTimestamps, logs, scheduling at a dateTimeouts, latency, rate limits

The rule from the Go design document is worth memorising: wall clocks are for telling time, monotonic clocks are for measuring time.

A diagram with two parallel timelines across the leap second: the wall clock counts 23:59:59, then repeats the same second before reaching 00:00:00, so an interval that starts before the step and ends after it measures as negative, while the monotonic clock simply keeps counting and measures the true positive duration.
The same interval measured with two clocks

The root cause: a negative duration

Here is where the two clocks meet DNS.

Cloudflare customers can point a name at another name using a CNAME record. To answer a query for such a name, RRDNS sometimes has to look up the target name itself, and it does that by asking one of several internal resolvers in the same data centre. A customer who uses an A record has entered the IP address directly, so no extra lookup is needed. That is why only CNAME users were affected.

RRDNS keeps track of how quickly each internal resolver responds and uses a weighted random choice to favour the fast ones. To measure response time, the code recorded the time when it sent a query and subtracted that from the time when the answer arrived. In outline (an illustration of the pattern, not Cloudflare's exact code):

start := time.Now()
// ... send query to the upstream resolver, wait for the reply ...
rtt := time.Now().Sub(start)   // assumed to be >= 0
upstream.updateRTT(rtt)        // feeds a smoothed average

In the Go of early 2017, time.Now() read only the wall clock. If the clock stepped back by a second between the two calls, the "later" reading was smaller than the earlier one. With illustrative numbers: a query sent at 23:59:59.990 and answered 30 milliseconds later, just after the step, would be stamped 23:59:59.020 on the second pass through that second. The subtraction gives minus 970 milliseconds.

Cloudflare explains that a single bad measurement was not the issue. RRDNS smooths many measurements per resolver, and after a few measurements the smoothed value itself became negative. That smoothed value fed the weighted selection, which called Go's rand.Int63n(). The documentation for that function says it panics if its argument is zero or negative. So every time the selection code ran with a negative weight, it panicked, and the lookup failed.

Notice how long the effect outlived its cause. The clock anomaly lasted one second. The bad value, however, was held in the server's memory, and as the eventual fix implies, the code had no step that would throw it away. The failures continued until fixed software was deployed. Impact ran from 00:00 to 06:45.

A side-by-side diagram of two DNS queries arriving at RRDNS: a name with an A record is answered directly from the stored IP address and was not affected, while a name with a CNAME record needs a lookup through an internal resolver chosen by weighted random selection, which is where the panic occurred.
Why only CNAME customers were affected

Why the safeguards did not catch it

The assumption was invisible. Nobody writes a comment saying "this assumes time does not go backwards". Cloudflare named exactly that belief as the root cause. In normal operation the subtraction is always positive, so tests pass and years of production traffic pass.

The trigger is rare. A leap second happens at most twice a year and often not for years. The previous one was on 30 June 2015. Code written or changed since then had never met one in production.

The language offered no safe default. Cloudflare noted that Go at the time gave programs no monotonic time source to use for this. The Go issue asking for one had been open since October 2015.

The safety net was partial. recover kept the process alive, which is better than a crash loop. But catching a panic does not answer the query. A handler that hides the error still leaves the request failed and the corrupted state in place.

What changed afterwards

Cloudflare's fix stopped negative values from being used in server selection: if time appears to have skipped backwards, RRDNS now discards what it knows about upstream performance and lets the measurements settle again. The most affected machines were patched within 90 minutes, and all RRDNS servers were restarted. Cloudflare also said it was inspecting the rest of its code for other places where time intervals were computed in a leap-second-sensitive way.

The more lasting change was in Go itself. The design document for monotonic time, last updated in January 2017, cites Cloudflare's DNS outage as part of its motivation. The solution, released in Go 1.9 on 24 August 2017, needed no new API. time.Now() now reads both clocks and stores both in the returned value. Printing the time uses the wall reading. Subtracting or comparing two times uses the monotonic readings when both have one. The code pattern that failed at Cloudflare became correct without anyone having to rewrite it.

The computer science underneath

Clocks in the kernel. A machine keeps time by counting ticks of a hardware oscillator and exposing several views of that count. The lesson on timers, clocks and timekeeping explains where those clocks come from and why there is more than one. The wall clock is corrected to match the outside world, and that correction is exactly what makes it unsafe as a stopwatch.

Clock synchronisation. Oscillators drift, so machines correct their wall clocks over the network using NTP, covered in SNMP, NTP and Syslog. NTP is also one of the ways a leap second announcement reaches a server. Any synchronised clock can be adjusted under your program's feet.

Time in distributed systems. If one machine's clock can step backwards, clocks on different machines certainly cannot be trusted to agree. That is why distributed systems often order events with counters instead of timestamps, as explained in logical clocks: Lamport and vector timestamps.

DNS and weighted selection. The failing code sat on the path that resolves a CNAME to an address; DNS, zones and delegation covers record types and how resolution proceeds. The selection among internal resolvers is a small load balancer: measure each backend, weight by performance, pick at random. Load balancing describes these strategies. Any weighted algorithm needs its weights validated, because a negative or zero weight has no meaning.

What an interviewer could ask from this

What is the difference between a wall clock and a monotonic clock? A wall clock tracks civil time and can be set or stepped, including backwards. A monotonic clock only moves forwards and has no meaningful absolute value. Use the first for timestamps and the second for durations.

How should you measure how long an operation took? Read a monotonic clock before and after and subtract. In Go 1.9 and later time.Since(start) does this. Elsewhere, use the equivalent of CLOCK_MONOTONIC, such as System.nanoTime() in Java or time.monotonic() in Python.

What is a leap second and how does Unix time deal with it? An extra second added to UTC to keep it within 0.9 seconds of the Earth's rotation. Unix time has no slot for it, so systems typically repeat a second or smear the adjustment over several hours.

Why did a one-second event cause hours of impact? The negative measurements were folded into a smoothed value held in memory. That state stayed bad after the clock was normal again, and it took a code fix and restarts to clear it.

The panics were recovered. Why did requests still fail? Recovering stops the process from dying. It does not complete the work that was in progress, and it does not repair the bad input that caused the panic.

How would you defend this code even without a monotonic clock? Validate at the boundary: clamp or discard negative durations, and check arguments before calling a function with a documented precondition, such as a strictly positive argument.

Takeaways

  • A wall clock can go backwards. Never subtract two wall clock readings to measure elapsed time.
  • "This value can never be negative" is an assumption. Either enforce it with a check or handle the case.
  • Bad data that enters long-lived state, such as a moving average, keeps causing harm after the original event is over.
  • Catching a panic keeps a server alive but does not make the failed request succeed.
  • Good defaults matter: after Go 1.9, the same code is correct without the programmer knowing about any of this.

Sources

  1. Cloudflare: How and why the leap second affected Cloudflare DNS
  2. IERS Bulletin C 52 (leap second announcement, 6 July 2016)
  3. Go proposal: Monotonic Elapsed Time Measurements in Go (Russ Cox)
  4. Go issue 12914: time: use monotonic clock to measure elapsed time
  5. Go 1.9 Release Notes
  6. Go Release History
  7. Go package documentation: math/rand, Int63n
  8. Linux manual page: clock_gettime(2)
  9. Wikipedia: Leap second

Written by the Codevizag Academy team

An independent explainer built from the public sources listed above. Codevizag Academy is not affiliated with Cloudflare. Found a mistake? Write to support@codevizag.com.

More case studies

Understood it? Now prove it.

The lessons behind this case study are free, and 20 problems a month are judged on real test cases at no cost.

Start solving free