App-vNext/Polly · error · ArgumentOutOfRangeException

The ttl for items to cache must be greater than zero.

Error message

The ttl for items to cache must be greater than zero.

What it means

Thrown by the legacy Polly v7 SlidingTtl constructor when the supplied TimeSpan is less than TimeSpan.Zero. SlidingTtl is an ITtlStrategy that marks cache entries with a sliding TTL; a negative sliding window is invalid, so Polly throws ArgumentOutOfRangeException. As with RelativeTtl, TimeSpan.Zero passes but yields an instantly-expiring entry.

Source

Thrown at src/Polly/Caching/SlidingTtl.cs:19

#nullable enable
namespace Polly.Caching;

/// <summary>
/// Defines a ttl strategy which will cache items with a sliding ttl.
/// </summary>
public class SlidingTtl : ITtlStrategy
{
    private readonly Ttl _ttl;

    /// <summary>
    /// Initializes a new instance of the <see cref="SlidingTtl"/> class.
    /// </summary>
    /// <param name="slidingTtl">The sliding timespan for which cache items should be considered valid.</param>
    public SlidingTtl(TimeSpan slidingTtl)
    {
        if (slidingTtl < TimeSpan.Zero)
        {
            throw new ArgumentOutOfRangeException(nameof(slidingTtl), "The ttl for items to cache must be greater than zero.");
        }

        _ttl = new Ttl(slidingTtl, true);
    }

    /// <summary>
    /// Gets a TTL for the cacheable item.
    /// </summary>
    /// <param name="context">The execution context.</param>
    /// <param name="result">The execution result.</param>
    /// <returns>A <see cref="Ttl"/> representing the remaining Ttl of the cached item.</returns>
    public Ttl GetTtl(Context context, object? result) =>
        _ttl;
}

View on GitHub (pinned to d0e46bdb1e)

Solutions

  1. Pass a non-negative sliding TimeSpan (positive recommended; zero is allowed but useless).
  2. Clamp configured sliding ttl to TimeSpan.Zero or a positive minimum before constructing SlidingTtl.
  3. Default to a sane positive value when config is missing/invalid.

Example fix

// before
new SlidingTtl(TimeSpan.FromMinutes(-5));
// after
new SlidingTtl(TimeSpan.FromMinutes(5));
Defensive patterns

Strategy: validation

Validate before calling

if (slidingTtl < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(slidingTtl), "sliding ttl must be non-negative.");
var strategy = new SlidingTtl(slidingTtl);

Type guard

static bool IsTtlValid(TimeSpan ttl) => ttl >= TimeSpan.Zero;

Prevention

When it happens

Trigger: Constructing new SlidingTtl(negativeTimeSpan); a sliding duration derived from configuration or computation that went negative.

Common situations: Sliding ttl misconfigured as negative in appsettings; a computed duration (end - now) that is negative because now is past end; arithmetic error producing -duration.

Related errors


AI-assisted analysis of App-vNext/Polly@d0e46bdb1e (2026-08-13). Data as JSON: /api/errors/633fbf372676813e. Report an issue: GitHub.