EST. 2026 — Notes from real server work SYSADMIN · SECURITY · AI · DIRECTADMIN Issue 01
THE SYSADMIN ALMANAC
Home / Linux / Data Rejected as -3.4 Seconds Old: PC Clock Behind NTP
Linux

Data Rejected as -3.4 Seconds Old: PC Clock Behind NTP

by Ton-Or ·1 Dec 2026·10 min read
Data Rejected as -3.4 Seconds Old: PC Clock Behind NTP

A negative data age does not mean bad data. It is evidence that the subtraction used two clocks. The rule I took from this work is one comparison, one clock.

1-minute summary

Symptom / problem
A freshness gate rejected data 4 times in a row because the age went negative, with the PC clock 3.7 s behind NTP
Who should read
Developers of systems that compare timestamps across machines
Fix in short
Prove it with w32tm, measure age from the time data arrives on our own machine, and audit every place that compares two clocks
Jump to steps

I had just installed a new version of a real-time data system I wrote for my own use. It is a desktop program on Windows, with an engine that receives data from an upstream source, a control interface written in C#, and a component that sends commands to a downstream system. After installation, I sent a command from the interface. The system rejected it. I tried again and got another rejection, for a total of 4 within one minute. The message said the latest data was stale, followed by -3.4 s in parentheses. I skimmed past that number twice before it struck me: how could data age be negative?

I have replaced the program name, channel names, and log messages with generic names, but every number is an actual measurement from my machine.

The symptom: 4 rejections in a row while the numbers kept moving

The system works like this: the engine receives data from the upstream source and places it in shared memory. The interface reads from there to display it. Commands I send from the interface pass through several gates in the engine before they are actually sent out. One is the freshness gate. If the latest data held by the engine is older than the limit, it rejects the command outright, because acting on stale data is more dangerous than doing nothing.

# log ของเอนจิน (เปลี่ยนชื่อช่องและข้อความเป็นชื่อกลางแล้ว) บรรทัดแบบนี้ 4 ครั้งในหนึ่งนาที
MANUAL refused: stale data on channel-a (-3.4 s)

The contradiction was that the numbers for the same channel were still changing every second on screen. Nothing suggested the data had stalled.

4 timesRejected in one minute
-3.4 sData age calculated by the gate
+3.69 sOffset measured with w32tm
10 s / 3 sLimits for the two gate levels

My first wrong guess: the data pipeline and shared memory

The word stale immediately sent me in the wrong direction. I guessed that the upstream data pipeline had stalled, or that the engine's shared memory reader was getting old values. Since I had just installed a new version, I suspected what had just changed. But that guess fell apart quickly, because the interface read from the same shared memory block as the engine, and the numbers on screen were still moving normally. If the pipeline had really stalled, the display would have frozen too.

What I should have caught immediately was the minus sign. Truly stalled data should have a positive age that keeps growing as time passes. What I saw instead was an age of -3.4 seconds. That is not a symptom of a stalled pipeline. It is a symptom of an offset between two things that should not have been subtracted from each other.

A negative value is a clue, not garbage

When a quantity that cannot be negative by definition, such as age, duration, or size, comes out negative, do not just clamp it and move on. First ask whether the two operands came from the same source. In this case, the -3.4 in the log was the only thing pointing to the root cause. If the original code had clamped negative values to zero and printed 0.0 s, I would have spent much longer searching.

The real cause: the gate subtracted readings from two clocks

I went back to the gate condition. It was written straightforwardly like this (the actual engine is written in another language; I translated the logic into C# for readability).

// ด่านเดิม: nowUs มาจากนาฬิกา PC ส่วน stampUs คือเวลาที่ระบบต้นทางประทับมากับข้อมูล
static bool IsFreshOld(long nowUs, long stampUs, long limitUs)
{
    long age = nowUs - stampUs;            // ลบกันข้ามนาฬิกาสองเรือน
    return age >= 0 && age <= limitUs;     // age = -3.4 s -> false ทุกครั้ง
}

stampUs is the time from the upstream server's clock, while nowUs is the time from my PC's clock. This single subtraction is valid only if the two clocks agree, which nobody guarantees. And the age >= 0 condition, added to guard against strange values, ended up rejecting everything when my clock was behind theirs.

I proved it with a tool already included in Windows.

# แหล่งเวลาที่บริการเวลาของ Windows ใช้อยู่
w32tm /query /source
# ผลบนเครื่องผม: Local CMOS Clock  (แปลว่าไม่ได้ sync กับใครเลย)

# สถานะการ sync ครั้งล่าสุด
w32tm /query /status

# วัด offset เทียบกับ NTP โดยไม่แก้นาฬิกา
w32tm /stripchart /computer:pool.ntp.org /samples:5 /dataonly
# ค่าที่ผมอ่านได้: +3.69 วินาที = นาฬิกา PC ช้ากว่า NTP

The Windows time service on this machine had never synced. Its time source was Local CMOS Clock, so the clock had drifted on its own until it was 3.7 seconds behind the actual time. Every incoming data item had a timestamp in my machine's "future." Adding 3.7 to -3.4 gives roughly 0.3 seconds, which would be the actual data age if the clocks agreed. Very fresh, but the gate saw a negative value.

Old: compare source timestamp with PC clockSource clockPC clock3.7 s slowStamp Tnow_pcAge = now_pc - T = -3.4 sT is in PC's futureNew: age since arrival, using one PC clockPC clockarrival_pcnow_pcAge = now_pc - arrival_pcMeasured 0.25-2.9 s, skew-independentT is for display only
Top: timestamp T from the source clock falls to the right of now on the PC clock, which is 3.7 seconds slow, so the age comes out as -3.4 seconds. Bottom: both the start and end of the age measurement use the same PC clock, so the skew cancels out completely.

I had never encountered this before because the previous version used a different form of the condition. The clock was already wrong, but no line of code had tripped over it until the version I had just installed.

The fix: change what is measured, not add an offset

The most immediate option was to measure the offset and add it to the formula. I rejected that approach because the offset is not constant. The day someone syncs the clock, it will jump from 3.7 to nearly zero in an instant, and the added correction will itself become the error. Simply syncing the clock and calling it done was not enough either, because that would fix only my machine. The code could break again whenever either clock drifted.

What I changed was the question the gate asked, from "How many seconds ago was this data timestamped?" to "How many seconds have passed since we last saw a new timestamp arrive?" Both the start and end of the age measurement use my own clock, so the skew cancels out without needing to know its value.

using System;
using System.Collections.Generic;
using System.Linq;

public sealed class ArrivalClock
{
    private readonly Func<long> _nowUs;          // นาฬิกาของเราเอง inject ได้ในเทสต์
    private long _lastStampUs = long.MinValue;
    private long? _movedUs;                      // null จนกว่าจะเห็นข้อมูลขยับครั้งแรก
    private readonly Queue<(long AtUs, long DiffUs)> _skew = new();

    public ArrivalClock(Func<long> nowUs) => _nowUs = nowUs;

    // เรียกทุกครั้งที่อ่านข้อมูลล่าสุดของช่องนั้นได้
    public void OnSample(long stampUs)
    {
        if (stampUs == _lastStampUs) return;     // เวลาประทับไม่ขยับ = ไม่ใช่ข้อมูลใหม่
        _lastStampUs = stampUs;
        long now = _nowUs();
        _movedUs = now;
        _skew.Enqueue((now, stampUs - now));
        while (_skew.Count > 0 && now - _skew.Peek().AtUs > 120_000_000) _skew.Dequeue();
    }

    // ด่านความสด: ทั้งสองปลายของอายุคือนาฬิกาเรือนเดียวกัน
    public bool IsStale(long limitUs)
    {
        if (_movedUs is not long moved) return true;   // ยังไม่เคยเห็นข้อมูลใหม่หลังเริ่มโปรแกรม
        long age = Math.Max(0, _nowUs() - moved);      // นาฬิกาถูกปรับถอยหลัง อ่านเป็น 0
        return age > limitUs;
    }

    // เวลาประทับ - เวลามาถึง ค่าสูงสุดในหน้าต่าง 120 วินาที
    public double? ClockSkewS => _skew.Count == 0 ? null : _skew.Max(x => x.DiffUs) / 1e6;
}

I deliberately included three details. First, the initial value is null, not the program's start time. If the data has not advanced even once since startup, it must be treated as not fresh, because the value sitting in shared memory could be from an hour ago. Second, setting the clock backward makes the subtraction negative. I read that as 0 instead of letting a negative value propagate through the system. Third, the same gate applies to every entry point. Normal commands use a 10-second limit, while commands arriving through an external port use 3 seconds. The source timestamp is now used only for display, no longer as a condition for anything.

Old

Age = my clock - their timestamp

Correct only when the two machines' clocks agree. A skew of 3.7 seconds makes the age negative and rejects every command. If my clock is ahead instead, the effect reverses: fresh data appears older than it really is.

New

Age = my clock - when I saw new data arrive

Both endpoints use the same clock, so the result is independent of skew. It answers what the gate actually needs to know: is the pipeline still delivering new data? The tradeoff is that it cannot tell how long the data sat at the source before being sent.

The tradeoff in the right-hand box needs to be explicit. The new method measures "continuity of arrivals," not "age since creation." If the source holds data for 5 seconds and then releases it steadily, this gate will consider it fresh. In my system, the risk the gate is meant to guard against is a broken or stalled pipeline, which the new method detects more directly. As for delays at the source, I can look at the separately reported skew value in the next section.

Report skew instead of rejecting commands

Once the gate no longer cared about skew, I did not want clock drift to disappear silently either. So I added a reported value named clock_skew_s, calculated from the difference (timestamp - arrival time), taking the maximum over a 120-second window.

I used the maximum rather than the average because each difference is the skew minus the data's transit time. Transit time is always positive and varies, so the item with the shortest transit time in the window gives the closest estimate of the actual skew.

{
  "channel": "channel-a",
  "status": "live",
  "clock": {
    "clock_skew_s": 3.67,
    "clock_skew_warn": true,
    "arrival_age_s": 0.25
  }
}

The system health screen displays this value per channel. It turns yellow when it exceeds 2 seconds in either direction, with advice to sync the clock using w32tm /resync. It never turns red, because nothing in the system rejects commands because of skew anymore. After installing the fixed version, I measured the same +3.67 seconds on every channel. Age since arrival ranged from 0.25 to 2.9 seconds, and the gate that had rejected commands at -3.4 seconds now passed them.

# ต้องรันด้วยสิทธิ์ผู้ดูแลเครื่อง
w32tm /config /manualpeerlist:"pool.ntp.org" /syncfromflags:manual /update
w32tm /resync
w32tm /query /source     # ต้องไม่ใช่ Local CMOS Clock แล้ว
Why I did not sync the clock first

Syncing requires administrator privileges and changes the state of the whole machine. I chose to make the code independent of skew first, then leave the skew value yellow on the system health screen. That also served as good evidence that the new gate worked correctly even with the clock still off by 3.67 seconds. If I had synced first and then changed the code, I would have had no way to know whether the new code really handled this or merely happened to pass.

Audit every place where source time meets local time

The most valuable part of this work, in my view, was not the fix itself but searching the entire codebase for other places that compared source time with local time. This kind of bug never appears in just one place. I then required each place to declare which clock it used.

Time comparison Required clock Notes
Freshness gate before sending commands (10 seconds and 3 seconds) Arrival time on the PC clock Fixed in this round
heartbeat between two processes on the same machine PC clock at both ends Same machine, already the same clock
Time window boundaries and data cycle cutoffs Source time only Offset estimated from incoming data, without reading the PC clock directly
Weekly scheduled jobs Both clocks, using the slower one as the reference Deliberately a two-stage gate
Times displayed on screen Any clock Display only, not a gate

The fourth row is a deliberate exception. Some jobs should run only when "the time has definitely arrived on both sides," so I use two clocks and wait for the slower one. This does not break the rule, because I am not subtracting the two clocks. Each clock is compared against its own threshold, and the results are then combined.

  1. Search the entire codebase for every variable containing an external time (source timestamps, file times, message header times), then follow every line where it is subtracted from or compared with local time.
  2. Answer two questions for each location: is this a gate that can reject work or merely a display, and do both sides of the comparison come from the same clock?
  3. For gates that use two clocks, change what is measured until only one clock remains. Do not fix them by adding an offset.
  4. Where source time is genuinely needed, such as data cycle cutoffs, use source time at both ends.
  5. Keep a table of the audit results in the work notes. Any new locations added later must go into the same table.
  6. Add a visible skew metric to the system health screen, but do not tie it to any gate.

Tests that lock in the behavior, and the wall clock tradeoff

All tests for the new gate use an injected clock. None actually sleep.

using Xunit;

public sealed class ArrivalClockTests
{
    [Fact]
    public void Freshness_Is_The_Arrival_Clock_Not_The_Remote_Stamp()
    {
        long now = 1_000_000_000;
        var c = new ArrivalClock(() => now);
        Assert.True(c.IsStale(10_000_000));           // ยังไม่เคยเห็นข้อมูล = ไม่สด

        c.OnSample(now + 5_000_000);                  // ประทับล่วงหน้า 5 วินาที แต่เพิ่งมาถึง
        Assert.False(c.IsStale(3_000_000));           // ต้องถือว่าสด
        Assert.Equal(5.0, c.ClockSkewS!.Value, 3);    // และรายงาน skew +5 วินาที

        now += 3_500_000;                             // ไม่มีข้อมูลใหม่ 3.5 วินาที
        Assert.True(c.IsStale(3_000_000));            // ด่าน 3 วินาทีปฏิเสธ
        Assert.False(c.IsStale(10_000_000));          // ด่าน 10 วินาทียังผ่าน

        now -= 60_000_000;                            // นาฬิกาถูกปรับถอยหลัง
        Assert.False(c.IsStale(3_000_000));           // อายุอ่านเป็น 0 ไม่ใช่ติดลบ
    }
}

The interface has another test for the display. A value of 3.69 must appear yellow with advice to sync. A value of -2.5 must also be yellow. A value of 0.4 must appear normal, and null must display as a dash. No case turns red.

One thing I need to state plainly is that the clock I use to measure arrival time is the machine's injectable wall clock, not a monotonic clock such as Stopwatch.GetTimestamp() or Environment.TickCount64. I chose this because the engine has one shared clock used by every component, and the entire test suite already injects time through it. The consequence is that if someone sets the machine's clock backward, the age reads as 0 until the clock catches up to its original position or new data arrives. Data that is actually stalled during that interval will appear fresh longer than it should. If the clock jumps forward, the age will briefly appear greater than it really is, until the next data item arrives and resets it. Both cases correct themselves when new data arrives, so I accepted that. If you are starting from scratch without my shared-clock constraint, using a monotonic clock from the outset would be cleaner, depending on what suits your system.

Time flow after the fixData arrivesWith timestamp T->Did T advance?No change = skip->Record arrivalPC clock->Freshness gatenow - arrival->Report skewT - arrival, no rejection

What I am taking forward

In summary, the bug was not that my machine's clock was slow. The slow clock was merely the trigger. The bug was subtracting readings from two different clocks in a single line, which passed every test because the tests always had only one clock. Time zone differences between an application and the person entering data are a similar-looking problem with a different mechanism. I covered that separately in the article about an app using UTC while people think in Thai time.

I now keep three rules in my work notes: use one clock per comparison; when a value that cannot be negative turns negative, log it as it is before clamping; and report clock drift as a warning instead of using it to reject work. I have not yet decided whether to move the gate to a monotonic clock. If I do and find anything else, or if I have left anything out of this explanation, I will come back and update it later.

Hit something like this? Stuck somewhere?

Come trade notes on the LinuxThai board

→ Continue on the board

Comments 0

No comments yet — be the first