Scrivio Interview library
CodingIntermediate5 min read · updated 12 November 2026

Measure elapsed time for a request handler. A colleague uses Duration.between(Instant.now(), ...) at start and end. Is that correct, and what would you use instead?

It mostly works, but it is the wrong clock. Instant.now() reads the wall clock, which NTP can correct by stepping it forwards or backwards, so a measured duration can be too long, too short or even negative. For elapsed time we use System.nanoTime(), which is monotonic within a JVM, and convert with Duration.ofNanos(end - start); metrics libraries such as Micrometer's Timer already do this, and Instant stays the right choice for recording when something happened.

Why this question is asked

Measuring how long something took sounds trivial, and the colleague's code looks reasonable: take the time at the start, take it at the end, subtract. Interviewers ask this because the bug it hides appears rarely, usually on a busy machine after a clock correction, and then produces latency graphs with impossible spikes or negative values. In this answer, we will recap the two kinds of clocks a computer offers, see how the wall clock can jump, measure correctly with nanoTime, and then look at how Micrometer handles it for us.

1A Quick Recap: Two Kinds of Clock

A computer keeps two different notions of time. The wall clock, also called real time, answers 'what time is it?'. It is the time we show to users and write into logs, and it must agree with the rest of the world, so it is corrected regularly by NTP, the Network Time Protocol, which compares it with reference servers.

The monotonic clock answers 'how much time has passed?'. It counts steadily from some arbitrary starting point, such as when the machine booted, and it never goes backwards. Its absolute value means nothing; only the difference between two readings does. In Java, Instant.now() and System.currentTimeMillis() read the wall clock, and System.nanoTime() reads the monotonic clock.

The two clocks Java gives us
Wall clockMonotonic clock
Java APIInstant.now(), currentTimeMillis()System.nanoTime()
Answerswhat time is it?how much time has passed?
Can jump?yes, NTP steps, manual changesno, never goes backwards
Meaningful alone?yes, a point in timeno, only differences
Use fortimestamps, logs, created_atlatency, timeouts, benchmarks

2How the Wall Clock Can Jump

NTP corrects small errors by slewing: it speeds up or slows down the wall clock very slightly until it agrees, which bends measurements a little. Larger errors, for example after a virtual machine resumes from a pause or when a host's clock has drifted, are often corrected by stepping: the clock jumps to the correct time at once, forwards or backwards. An operator changing the time by hand does the same.

If a step happens between the two readings, the measurement includes the step. Here is what the colleague's code reports when the clock is stepped back by two seconds during a 120 millisecond request.

Java
Instant start = Instant.now(); // 10:00:05.000
handle(request); // takes 120 ms; NTP steps the clock back 2 s meanwhile
Instant end = Instant.now(); // 10:00:03.120
Duration took = Duration.between(start, end);
System.out.println(took); // PT-1.88S: a negative latency

Notice that nothing threw an exception. The value simply went into a log or a metric, where a negative or hugely inflated latency is hard to explain later. On a well-run server this is rare, which is exactly why it survives code review.

3Measuring Elapsed Time Correctly

For elapsed time we read the monotonic clock twice and subtract. System.nanoTime() returns a long count of nanoseconds from an arbitrary origin, guaranteed not to go backwards within one JVM. We then wrap the difference in a Duration so it prints and converts nicely.

Java
long start = System.nanoTime();
handle(request);
long end = System.nanoTime();
Duration took = Duration.ofNanos(end - start);
System.out.println(took); // PT0.120345S
System.out.println(took.toMillis()); // 120
Step throughChoosing a clock for a time value
  1. Is it a point in time?shown to people, stored, compared across machines
    YesInstant.now(clock), wall clockNoIt is an amount of elapsed time
  2. Measured inside one JVM?
    YesSystem.nanoTime() or a metrics TimerNoEach side records Instants; accept clock skew

2 steps in order. Play them, or step through them one at a time.

Notice that we always subtract and never compare nanoTime values directly with less-than; the documentation recommends end - start because the raw number can overflow in theory, and subtraction stays correct across that. The value also means nothing across JVMs or machines, so we never store it or send it to another service. The resolution of nanoTime depends on the operating system, so for very short operations we use a benchmark tool such as JMH rather than a single measurement.

4Let Micrometer Do It

In a Spring Boot service we rarely need to write this by hand. Micrometer's Timer measures with its Clock's monotonic time, which is nanoTime by default, and records the result into a histogram we can graph and alert on. Spring Boot already times every HTTP request this way in the http.server.requests metric, so for a handler we may only need custom timers around specific steps.

Java
Timer.Sample sample = Timer.start(registry); // reads the monotonic clock
handle(request);
sample.stop(registry.timer("orders.handle", "outcome", "ok")); // records 120 ms
// or simply
registry.timer("orders.handle").record(() -> handle(request));

Using Timer also gives us percentiles, counts and maximums for free, which a single logged Duration never would.

5Where Instant Still Belongs

None of this makes Instant wrong. It is the right type for recording when something happened: the request arrived at 10:00:05Z, the order was created at 10:00:05.120Z. Those values must agree with other machines and with people, so they need the wall clock, corrections and all. A useful pattern is to record both: an Instant for when the request started, for logs and tracing, and a nanoTime-based Duration for how long it took.

6Follow-up questions

Why does Duration.between with Instant usually give the right answer?

Because the wall clock usually only slews by tiny amounts. Steps happen rarely: after VM pauses, on badly synced hosts, or by hand. So the bug shows up as occasional outliers rather than consistent errors, which makes it easy to miss and hard to debug.

Can we compare nanoTime values from two different servers?

No. Each JVM's origin is arbitrary, so the numbers are unrelated. To measure across services, each side records wall-clock Instants and we accept the clock skew between machines, or better, we use distributed tracing, which records each span's duration locally with a monotonic clock and its start time with the wall clock.

Is System.currentTimeMillis() any better than Instant.now()?

No. It reads the same wall clock, with millisecond resolution, so it has the same jump problem. It is fine for timestamps and wrong for measuring elapsed time.

7Conclusion

In this answer, we saw that Instant.now() reads the wall clock, which NTP and operators can step forwards or backwards, so a duration computed from two Instants can be inflated or even negative. For elapsed time we use the monotonic System.nanoTime(), subtract the readings and wrap the difference with Duration.ofNanos. Micrometer's Timer already measures this way and gives us percentiles too. Instant remains the right type for recording when something happened, and recording both kinds of value is often the best answer.

What to say in the interviewAbout 70 seconds aloud

Open with

It works most of the time, but it uses the wrong clock. Instant.now reads the wall clock, the same one as currentTimeMillis, and that clock is corrected by NTP.

Then, if they want more

Small corrections are slewed, but larger ones, for example after a VM pause, can step the clock forwards or backwards, and then Duration.between gives an inflated or even negative latency. For elapsed time I would use System.nanoTime, which reads a monotonic clock that never goes backwards within the JVM.

I take a reading at the start and at the end, subtract them, and wrap the result with Duration.ofNanos so it is readable, for example toMillis for logging. The raw nanoTime value has an arbitrary origin, so I never store it or compare it across JVMs.

In a Spring Boot service I would usually not write this myself: Micrometer's Timer uses monotonic time, and Boot already records http.server.requests, so I would add a Timer around the specific step I care about and get percentiles too.

Instant is still the right choice for recording when something happened, like the request's start time in a log, so I often record both.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Measure elapsed time for a request handler. A colleague uses...": https://scrivio-interview-library.netlify.app/java/date-and-time/618e0973d2/