Go / Basic: Values and Program Contracts / Lesson 7
Durations and time boundaries
Parse Go durations with explicit units and boundary checks.
On this page
Lesson goals
- Distinguish durations from instants.
- Parse and validate a duration.
- Parse durations while separating syntax, application bounds and representation limits.
- Distinguish deadlines, intervals and monotonic clocks and design controlled cancellation tests.
Distinguish duration and instant
A time interval and a clock reading answer different questions. time.Duration represents an elapsed interval, while time.Time represents an instant with associated location information. Keep the unit explicit at an input boundary and decide whether zero or negative durations are valid for the operation. Avoid storing an unexplained integer when another reader cannot tell whether it means seconds or milliseconds.
Use explicit units
Duration constants make units visible in calculations. The example multiplies a fixed count by time.Second and compares the result to two seconds. It uses no sleep or current clock, so the result is deterministic. Check the allowed range before multiplying a value obtained from external input; a named unit does not itself prevent integer overflow in the underlying duration representation.
package main
import (
"fmt"
"time"
)
func main() {
delay := 2 * time.Second
fmt.Println(delay == 2000*time.Millisecond)
}
true
Two seconds equals two thousand milliseconds.
Parse duration input
ParseDuration accepts text with duration units and returns an error for invalid input. The example checks the error before using the parsed result. A configuration interface should document which values it accepts and apply its own range policy after parsing. Parsing a syntactically valid negative duration does not mean a negative timeout is meaningful for every operation.
package main
import (
"fmt"
"time"
)
func main() {
delay, err := time.ParseDuration("1500ms")
if err != nil {
fmt.Println("invalid duration")
return
}
fmt.Println(delay == 1500*time.Millisecond)
}
true
Parsing succeeds and the duration equals the expected value.
Relate deadlines and intervals
A deadline is an instant by which work should finish; a duration is the interval used to derive or configure one. Time zones affect presentation and interpretation of local clock values, while elapsed-time questions require a consistent measurement strategy. Prefer passing a duration or context deadline through an API rather than recomputing independent timeouts at every layer.
Test time boundaries
Test valid units, invalid text, zero, a negative value if the parser accepts it, and the application’s upper bound. Use fixed durations for arithmetic tests rather than waiting for wall-clock time. For actual timeout behavior, coordinate the test with controlled work and allow for scheduling variation. A test that sleeps for an exact interval can be unreliable on a busy machine.
Model intervals before arithmetic
A duration measures an interval, not a calendar date or a clock reading. In Go, time.Duration is a signed count of nanoseconds represented by an int64; named constants such as time.Second and time.Millisecond give arithmetic a visible unit. Compare or combine quantities only after deciding what they mean. A duration of two seconds equals 2,000 milliseconds, while an instant such as 12:00 UTC identifies a point on a timeline. A deadline is an instant derived from a start and an allowed interval, not a duration by itself.
External integers need a documented unit and a range before conversion. If a configuration field says milliseconds, validate the count before multiplying by time.Millisecond so the multiplication remains representable and within the application’s policy. A large integer multiplied first may overflow the underlying signed representation; checking the already-overflowed value cannot reliably reconstruct the input. Choose a sensible maximum, test the maximum and the next value, and handle zero and negative input according to the operation rather than assuming one policy fits every use.
Separate syntax from domain policy
ParseDuration reads a signed sequence of decimal numbers and units such as ns, us, µs, ms, s, m and h; a unitless zero is also accepted. Compound input such as 1h30m represents the sum of its components. The parser reports an error for malformed text or values outside its representable duration range. Check that error before using the result, and return useful context at the configuration boundary. Do not invent a day unit: a calendar day is not always an elapsed 24-hour interval in every location.
Syntactic acceptance is not application approval. For example, -1s is a valid parsed duration but a service may require a strictly positive timeout no greater than 30s. Apply those bounds after successful parsing and before creating a timer or modifying configuration. Define whether zero means disabled, immediate or invalid; different APIs can use different semantics. Test malformed input, each allowed endpoint and values just outside it so that the parser’s contract and the domain rule remain visibly separate.
Share a deadline rather than resetting a budget
A timeout is an interval allowed for work; a deadline is the instant at which that allowance ends. If a request starts at a fixed instant and has a five-second budget, deriving one deadline and passing it through dependent operations prevents each layer from receiving a new independent five seconds. The remaining budget decreases as work proceeds. A child context cannot extend an earlier parent deadline; cancellation or an earlier deadline can stop it sooner. Call the cancellation function when finished to release associated resources, even if the operation completes early.
Timeout policy must also describe what the operation does when the deadline arrives. A context signals cancellation, but a dependency must cooperate with it; merely creating a context cannot force arbitrary work to stop. A timeout after a write was sent may leave the business outcome unknown, so a retry policy may need an operation identifier or a status check rather than repeating an effect blindly. Use an isolated fake for such exercises and distinguish a cancellation signal from proof that an external write did or did not commit.
Distinguish elapsed time and presentation
A time.Time can carry wall-clock and, when available, monotonic-clock readings. Values from time.Now normally carry both; operations such as Sub use monotonic readings when both operands have them, making elapsed measurement robust to wall-clock adjustments. Serialized forms omit the monotonic reading, so a parsed or decoded instant may be compared using wall-clock data instead. Know which values your measurement crosses and do not assume an arbitrary stored timestamp preserves a monotonic component.
Location affects how an instant is represented as local date and clock time. Two differently displayed values can denote the same instant; use Time.Equal for instant equality rather than comparing a formatted string or relying on the == operator’s additional representation details. Calendar operations and fixed elapsed intervals answer different questions: adding 24 hours is a duration operation, whereas moving to the same local time on the next calendar day can cross a daylight-saving transition. State the location and expected rule before testing either behavior.
Test boundaries without invented timing evidence
Pure duration arithmetic and parsing can be tested with fixed inputs and exact expected values, without sleeping or consulting the current clock. A practical table covers accepted units, compound input, malformed input, zero, negative input and the application’s maximum. Check errors before comparing a parsed result. If a helper converts an external count, include a rejected out-of-range input before multiplication and verify that previous valid configuration remains unchanged on failure.
For behavior involving a deadline, coordinate controlled work with channels or a fake dependency and assert the observable cancellation or completion path rather than exact scheduler timing. Give the test a generous outer bound so a regression cannot hang forever, and avoid assuming a timer fires at an exact nanosecond on a busy machine. Test the already-expired case and a normal completion separately; record the environment if an actual integration claim is made. The fixtures below are unexecuted traces, not measured timing results.
20 worked examples
1. Milliseconds to seconds
Problem: Compare 750 milliseconds with three quarters of a second.
- One second contains 1,000 milliseconds.
- Three quarters of 1,000 milliseconds is 750 milliseconds.
750*time.Millisecond == 3*time.Second/4
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The two fixed durations are equal.
Why this result follows: Both expressions describe the same elapsed interval.
2. Compound parse
Problem: Parse the fixed text 1h30m.
- The text supplies one hour and thirty minutes.
- The parser adds the two duration components.
time.ParseDuration("1h30m")
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Parsing succeeds with a duration of 90 minutes.
Why this result follows: Both h and m are supported duration units.
3. Decimal unit
Problem: Parse the fixed text 1.5s and express it in milliseconds.
- The s suffix identifies seconds.
- One and a half seconds equals 1,500 milliseconds.
time.ParseDuration("1.5s")
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Parsing succeeds with 1500ms.
Why this result follows: A decimal quantity can be attached to a supported unit.
4. Negative syntax
Problem: Parse -2s where a separate timeout policy requires a positive value.
- The parser accepts the signed duration text.
- The resulting negative duration fails the stated positive policy.
parse "-2s"; policy d>0
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Parsing succeeds but the application rejects the timeout.
Why this result follows: Syntax validity and domain validity are distinct checks.
5. Zero syntax
Problem: Parse unitless 0 under a policy that treats zero as disabled.
- ParseDuration accepts zero without a unit.
- The application assigns the accepted zero its disabled meaning.
parse "0"; policy zero=disabled
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Parsing succeeds and the setting is disabled.
Why this result follows: The zero meaning comes from the application contract.
6. Missing unit
Problem: Parse the nonzero text 12 without a unit.
- The nonzero quantity has no duration unit.
- The syntax requires a unit for this value.
time.ParseDuration("12")
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Parsing returns an error.
Why this result follows: A bare nonzero number is not a valid duration string.
7. Unsupported day
Problem: Parse the duration text 1d.
- The suffix d is not among ParseDuration units.
- A calendar day is not introduced by this parser syntax.
time.ParseDuration("1d")
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Parsing returns an error.
Why this result follows: The parser does not define d as a duration unit.
8. Upper bound
Problem: Apply a policy accepting durations greater than zero and at most 30s to 30s.
- The supplied duration is strictly greater than zero.
- It equals the upper bound, which the policy explicitly includes.
d=30*time.Second; accept if d>0 && d<=30*time.Second
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The application accepts 30s.
Why this result follows: The upper comparison includes the boundary.
9. Above upper bound
Problem: Apply the same positive and at-most-30s policy to 30s plus 1ns.
- The duration is positive but exceeds 30 seconds.
- The upper-bound comparison therefore fails.
d=30*time.Second+time.Nanosecond; accept if d>0 && d<=30*time.Second
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The application rejects the parsed duration.
Why this result follows: A representable duration can still violate application policy.
10. Overflow prevention
Problem: Convert an external millisecond count under a policy of 0 through 60000.
- The input exceeds the explicitly permitted maximum.
- The guard rejects it before the multiplication occurs.
count=60001; check 0<=count<=60000 before count*time.Millisecond
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The conversion is not performed and an error is returned.
Why this result follows: Pre-multiplication validation protects the policy and conversion boundary.
11. Duration arithmetic
Problem: Add a fixed 250ms to a fixed 2s interval.
- The two-second interval contains exactly 2,000 milliseconds.
- Adding another 250 milliseconds gives a total of 2,250 milliseconds.
2*time.Second + 250*time.Millisecond
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The total is 2250ms.
Why this result follows: Named duration units let the intervals be combined directly.
12. Fixed deadline
Problem: A request begins at 12:00:00 UTC with a five-second budget.
- The allowance is an interval measured from the start.
- Adding five seconds places the deadline five seconds later.
start=12:00:00 UTC; deadline=start+5s
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The deadline is 12:00:05 UTC.
Why this result follows: Adding a duration to an instant produces another instant.
13. Remaining budget
Problem: A five-second deadline is shared; two seconds of the budget have elapsed.
- The deadline remains fixed at five seconds after start.
- Subtracting the current offset of two seconds leaves three.
start=0s; deadline=5s; now=2s; remaining=deadline-now
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The remaining budget is 3s.
Why this result follows: Sharing a deadline avoids restarting the original interval.
14. Parent deadline
Problem: A child requests a ten-second timeout under a parent deadline three seconds away.
- The parent deadline occurs before the requested child timeout.
- The child cannot outlive that earlier parent deadline.
parent deadline=now+3s; child timeout=10s
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The effective deadline is no later than the parent deadline.
Why this result follows: A child context inherits cancellation from its parent.
15. Fixed-zone equality
Problem: Compare 12:00 UTC with 14:00 at a fixed UTC+02:00 offset on the same date.
- The second local clock is two hours ahead of UTC.
- Subtracting its offset places it at 12:00 UTC.
A=2024-01-01 12:00 UTC; B=2024-01-01 14:00 +02:00; A.Equal(B)
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: A.Equal(B) is true.
Why this result follows: Equal compares the instants despite different presentations.
16. Duration versus calendar
Problem: A local day has a spring clock change and is 23 elapsed hours long in the stated fixture.
- The calendar boundary is specified as 23 elapsed hours away.
- Adding 24 hours advances one hour beyond that boundary.
fixture: local midnight day 1 to next local midnight = 23h; compare Add(24h)
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: Add(24h) is one hour later than the next local midnight.
Why this result follows: A fixed elapsed interval need not equal a local calendar day.
17. Monotonic serialization
Problem: A time.Now value is serialized and parsed back. What happens to its monotonic reading?
- The original value may carry a monotonic reading.
- The serialized form omits that process-local reading.
t=time.Now(); encoded=serialize(t); parsed=decode(encoded)
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The parsed value does not retain the original monotonic reading.
Why this result follows: Serialization records wall-time representation rather than the monotonic component.
18. Elapsed subtraction
Problem: Two time.Now-derived values both retain monotonic readings; compute their elapsed interval with Sub.
- Both operands retain their monotonic components in the stated fixture.
- Sub uses those components for their elapsed comparison.
start=time.Now(); end=later time.Now(); elapsed=end.Sub(start)
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The result is the monotonic elapsed duration between the readings.
Why this result follows: The monotonic measurement avoids relying solely on wall-clock changes.
19. Controlled cancellation
Problem: A fake worker blocks until its context is cancelled, then reports cancellation.
- The ready signal ensures the fake has started before cancellation.
- The fake observes cancellation and reports its controlled outcome.
start fake; wait until ready; cancel context; receive fake result
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The test receives a cancellation result without relying on exact sleep timing.
Why this result follows: Synchronization makes the observed path explicit.
20. Unknown write outcome
Problem: A simulated write request times out after sending; no commit status is available.
- A timeout proves the caller stopped waiting, not whether the write committed.
- Without an idempotency or status contract, repeating the effect could duplicate it.
send operation K; timeout; status unavailable; no automatic replay
The fixture specifies time values and steps without claiming execution or a timing measurement.
Expected result: The outcome is reported as unknown and the operation is not blindly replayed.
Why this result follows: Cancellation evidence does not determine a remote business outcome.
Common errors and fixes
A timeout uses the wrong unit
- Why it happens
- A bare integer had no documented unit.
- How to fix it
- Convert using the intended duration unit.
- Prevent it next time
- Name units at API boundaries.
Invalid duration text is accepted
- Why it happens
- The parsing error was ignored.
- How to fix it
- Handle the ParseDuration error.
- Prevent it next time
- Test malformed input.
A test fails intermittently
- Why it happens
- It assumes exact scheduler timing.
- How to fix it
- Coordinate with controlled work.
- Prevent it next time
- Avoid exact sleep-based assertions.
20 practice exercises
1. How many milliseconds are in two seconds?
Show hint
Each second contains one thousand milliseconds.
Show worked solution
Two thousand. Multiplying by named duration constants makes the unit conversion visible.
Two seconds is 2 × 1000, or 2000 milliseconds. The comparison can use 2*time.Second and 2000*time.Millisecond without reading a clock or waiting.
Check your solution
- 2*time.Second equals 2000*time.Millisecond.
- The numeric result in milliseconds is 2000.
2. Why validate a parsed negative timeout?
Show hint
Separate acceptance of syntax from the application’s timeout rule.
Show worked solution
Valid duration syntax does not establish that the value is meaningful for the application. Enforce the domain rule separately.
A negative duration such as -1s can parse successfully, but an application may require a positive timeout. Check the parsing error first, then enforce the domain rule and report rejection without applying the invalid setting.
Check your solution
- -1s is syntactically accepted as a negative duration.
- A positive-timeout policy rejects it without updating configuration.
3. A configuration field delay_ms contains 1250. Express it as a Go duration and compare it with one second without reading the clock.
Show hint
The field’s documented unit is milliseconds.
Show worked solution
After validating the count, multiply by time.Millisecond to obtain 1250ms. It is greater than one second by 250ms. Use fixed arithmetic in the test rather than sleeping, and include the zero boundary required by the configuration policy.
Check your solution
- The resulting duration equals 1250ms.
- It exceeds time.Second by 250ms.
4. A field named retry_count is accidentally multiplied by time.Second. Explain the unit error and redesign the configuration for a retry delay.
Show hint
A count of attempts is not an elapsed interval.
Show worked solution
Keep retry_count as a dimensionless number of attempts and introduce a separately named retry_delay with an explicit duration unit. Validate each according to its own domain; for example, three attempts and a two-second delay are distinct settings. Test that changing one does not silently change the other.
Check your solution
- The attempt count remains a count rather than a duration.
- The delay has an explicit unit and independent validation.
5. Parse "2m15s" and compare it with 135 seconds. Include how the caller handles malformed input.
Show hint
Add the minute and second components only after checking the parse error.
Show worked solution
Two minutes is 120 seconds, and the extra 15 seconds makes 135 seconds. Check ParseDuration’s error before comparing the result; for malformed text return a configuration error rather than using the zero result as a valid timeout.
Check your solution
- The valid compound text equals 135 seconds.
- Malformed text takes the error path without applying a timeout.
6. A timeout must be between 100ms and 10s inclusive. Classify "99ms", "100ms", "10s" and "10001ms" after parsing.
Show hint
Apply inclusive comparisons after successful parsing.
Show worked solution
All four strings are syntactically valid durations. Accept 100ms and 10s, and reject 99ms and 10001ms because they fall just outside the stated interval. Keep parse errors distinct from valid values rejected by policy.
Check your solution
- Both endpoints are accepted.
- Both adjacent outside values are rejected by the policy.
7. A system accepts "0" as disabling retries and requires positive delays otherwise. Compare "0", "-1ms" and "1ms".
Show hint
The application may assign an explicit meaning to zero.
Show worked solution
Parsing accepts all three forms. Interpret zero as disabled, reject -1ms under the policy, and accept 1ms as a positive delay. Check the parser error first, then apply these three branches; do not treat every parsed duration as usable.
Check your solution
- Zero selects disabled and -1ms is rejected.
- 1ms is accepted as a positive delay.
8. A user enters "3d" for a fixed-duration setting. Explain the parse result and offer a documented alternative for 72 elapsed hours.
Show hint
ParseDuration does not define a d unit.
Show worked solution
The parser rejects 3d because d is unsupported. If the contract means exactly 72 elapsed hours, ask for 72h and validate that duration; if it means three local calendar days, use a separately specified calendar operation and location instead of silently equating the two.
Check your solution
- 3d produces a parse error.
- 72h is accepted syntactically as 72 elapsed hours.
9. An external integer milliseconds field allows 1 through 60000. Design the order of parsing, validation and multiplication, including failure state.
Show hint
Check the count before multiplying by the duration unit.
Show worked solution
Parse the integer with error reporting, reject syntax errors and counts outside 1..60000, and only then multiply by time.Millisecond. Preserve the previous configuration on any failure. Test 1, 60000, 0 and 60001; the chosen bound also keeps these products representable.
Check your solution
- The two endpoints are accepted and multiplied safely.
- Outside values or malformed text leave the previous setting unchanged.
10. A request starts at 09:30:00 UTC with an eight-second deadline budget. A first step takes three seconds. Compute the shared deadline and remaining budget.
Show hint
The deadline remains fixed while the remaining duration shrinks.
Show worked solution
The deadline is 09:30:08 UTC. After three seconds the instant is 09:30:03 and five seconds remain; passing the original deadline prevents the next step from receiving a fresh eight seconds. Test these fixed instants without a real sleep.
Check your solution
- The deadline is 09:30:08 UTC.
- The remaining budget after three seconds is 5s.
11. A parent deadline is two seconds away and a child asks for a five-second timeout. Compare this with a child asking for one second.
Show hint
The effective child deadline cannot exceed the parent deadline.
Show worked solution
The five-second request remains bounded by the earlier parent deadline, at most two seconds away. A one-second child timeout has its own earlier deadline, subject to cancellation or scheduling. Test both relationships rather than assuming the requested timeout always wins.
Check your solution
- The five-second child cannot outlive the parent deadline.
- The one-second child has an earlier requested deadline than the parent.
12. A worker ignores the context passed to it. The caller’s deadline expires. What can be concluded, and how would you test a cooperative alternative?
Show hint
A cancellation signal does not forcibly stop arbitrary work.
Show worked solution
The caller can observe deadline cancellation, but cannot conclude that the ignoring worker stopped. Build a fake that waits for ctx.Done and reports its exit; coordinate readiness before cancellation and verify the report under a generous outer test bound. Separately document behavior of any real dependency.
Check your solution
- The ignoring worker is not claimed to have stopped merely from cancellation.
- The cooperative fake reports exit after observing ctx.Done.
13. A simulated save times out and a later status check reports committed. Design the user response and explain why automatic replay is unnecessary.
Show hint
A timeout does not by itself determine the save outcome.
Show worked solution
Report the confirmed committed result using the operation reference, then refresh the displayed state if needed. Do not issue another save for the same effect merely because the response timed out. Test timeout, committed status and absence of a second write with a controlled fake.
Check your solution
- The committed result is shown after the status check.
- No duplicate save is issued in this recovery path.
14. Two timestamps show 08:00 UTC and 10:00 at fixed UTC+02:00 on the same date. Compare the instants and choose an appropriate Go comparison.
Show hint
Convert the local presentation to UTC or compare instants directly.
Show worked solution
The offset presentation corresponds to 08:00 UTC, so the instants are equal. Use Time.Equal for instant equality rather than comparing formatted strings or assuming == ignores location and monotonic representation. Test both equal instants and one instant one second later.
Check your solution
- Time.Equal reports the two stated instants equal.
- The instant one second later is not equal.
15. A local calendar day in a controlled fixture lasts 25 elapsed hours because clocks move back. Compare adding 24 hours with reaching the next local midnight.
Show hint
A calendar day and a fixed duration can have different lengths.
Show worked solution
The next local midnight is 25 elapsed hours after the first in this fixture. Adding 24 hours therefore lands one hour before that boundary. Use a documented location and calendar operation when the requirement is the next local date, and do not infer a universal day length.
Check your solution
- The fixture’s next midnight is 25 elapsed hours away.
- Adding 24 hours lands one hour before that midnight.
16. A program serializes a time.Now timestamp and later subtracts the parsed value from a new time.Now value. Explain why it cannot assume both values retain monotonic readings.
Show hint
Serialization removes the monotonic component.
Show worked solution
The encoded and parsed timestamp lacks the original monotonic reading, so the subtraction cannot use monotonic readings from both operands and follows the documented wall-time comparison behavior. For in-process elapsed timing retain suitable time.Now-derived values; document any cross-process wall-clock assumptions.
Check your solution
- The parsed value has no retained original monotonic reading.
- The elapsed calculation does not claim two monotonic operands.
17. An exact test sleeps 10ms and expects a timeout callback at precisely 10ms. Replace it with a coordinated behavior test and a bounded failure path.
Show hint
Test the event and outcome rather than exact scheduler timing.
Show worked solution
Use a fake that signals readiness and waits for cancellation; trigger the cancellation or controlled deadline and wait for its result. Add a generous outer timeout to prevent a hang, and assert the cancellation result rather than an exact elapsed nanosecond count. Keep a separate fixed arithmetic test for 10ms.
Check your solution
- The fake signals readiness and reports cancellation.
- The outer bound fails a hang without requiring an exact firing instant.
18. A timeout configuration currently holds 5s. An update supplies "bad". Design the update so failure does not replace the previous value.
Show hint
Parse and validate a candidate before committing configuration.
Show worked solution
Parse the new text into a temporary duration and check its error and domain before assigning it to the live setting. The malformed input returns an error and leaves 5s intact; a valid allowed value can then replace it. Test both failure and success.
Check your solution
- The malformed update returns an error and preserves 5s.
- A valid allowed update replaces the setting.
19. A context with a timeout finishes its work early. Explain why the caller should still call its returned cancel function and how to structure the call.
Show hint
Cancellation releases resources associated with the derived context.
Show worked solution
Call cancel when the operation is finished, commonly with defer cancel immediately after creating the derived context when the function scope is appropriate. Early completion does not remove the caller’s responsibility to release associated resources. Test the normal return path and a failure return path for cleanup.
Check your solution
- Both normal and error paths invoke the cancellation function.
- The operation does not wait for the deadline merely to release its context resources.
20. A service accepts a timeout greater than zero and up to 1m. Construct a compact table covering parser errors, zero, negative, endpoints and an over-limit input.
Show hint
Separate expected parse success from policy acceptance in each row.
Show worked solution
Include malformed "abc" as parse failure; "0" and "-1s" as parsed but rejected; a small positive duration such as "1ns" and "1m" as accepted; and "1m1ns" as parsed but over the limit. Check the error before applying the policy and verify rejected updates preserve prior state.
Check your solution
- The table distinguishes parse failure from policy rejection.
- It covers zero, negative, positive lower case, upper endpoint and over-limit input.
Key takeaways
- Use explicit units and distinguish instants from intervals.
- Handle parsing errors and domain limits.
- A duration represents a unit-bearing interval, not a calendar instant.
- Parsed inputs still require a separate domain policy.
- A timeout does not establish the outcome of a remote write.