<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mehmet Can Akay on Medium]]></title>
        <description><![CDATA[Stories by Mehmet Can Akay on Medium]]></description>
        <link>https://medium.com/@mehmetcan.akay4?source=rss-3e6aaab1d2e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Sl-l530yPuXANbdk.</url>
            <title>Stories by Mehmet Can Akay on Medium</title>
            <link>https://medium.com/@mehmetcan.akay4?source=rss-3e6aaab1d2e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:34:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehmetcan.akay4/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Configuration-Driven Recurring Jobs in Hangfire — and Skipping Overlaps Instead of Waiting for Them]]></title>
            <link>https://medium.com/@mehmetcan.akay4/configuration-driven-recurring-jobs-in-hangfire-and-skipping-overlaps-instead-of-waiting-for-them-6f93f358ca57?source=rss-3e6aaab1d2e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f93f358ca57</guid>
            <category><![CDATA[hangfire]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Mehmet Can Akay]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 20:16:47 GMT</pubDate>
            <atom:updated>2026-10-07T20:29:07.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uimn7FENcmAkROyrh8nvPQ.png" /></figure><h4>Notes from running a small Hangfire worker for a data-integration service: schedules declared in configuration, a filter that drops overlapping runs, and the edge cases that come with both.</h4><p>Our integration service moves survey and employee data between internal SQL Server databases and an external survey platform. A handful of recurring jobs do the work: push new survey invitees a few times a day, sync employee metadata every morning, pull survey answers once a week.</p><p>Hangfire handles this well. Two operational problems kept coming back, though:</p><ol><li><strong>Schedules lived in code.</strong> Moving a job from 09:00 to 07:00, or switching one off while the remote API was down, meant a code change and a release.</li><li><strong>Long runs overlapped the next trigger.</strong> When a sync took longer than its interval, the next instance started while the previous one was still running, or waited for it.</li></ol><p>This post describes the setup we ended up with. None of the individual pieces are new the value is in how they fit together, and in the edge cases we had to handle. I’ve tried to be explicit about the trade-offs, because a few of them are real.</p><h3>1. A Separate Worker Host</h3><p>Hangfire runs in its own ASP.NET Core process. The public API has no Hangfire packages at all.</p><pre>Solution/<br>├── YourApp.Api/          # ASP.NET Core API, no Hangfire<br>├── YourApp.Hangfire/     # Hangfire server + dashboard<br>├── YourApp.Service/      # Business logic shared by both hosts<br>├── YourApp.Integration/  # Outbound HTTP clients<br>├── YourApp.Data/         # Repositories<br>└── YourApp.Core/         # Configuration, logging, helpers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keKHgFRQ3UY3-Hk0geBKxw.png" /></figure><p>Both hosts call the same services. A job is just another caller of IInviteesService, the same as a controller is.</p><p>The benefit is a separate failure domain. A job that leaks memory, exhausts the thread pool, or floods the logs does not affect API latency, and the worker can be restarted or redeployed without touching user-facing traffic.</p><p>The cost is that you now maintain two composition roots and two deployments. For a solution with only a couple of light jobs, running Hangfire inside the API is a perfectly reasonable choice.</p><h3>2. Declaring Jobs in Configuration</h3><p>Instead of one RecurringJob.AddOrUpdate(...) call per job, every job is described in appsettings.{Environment}.json:</p><pre>public class HangfireSettings<br>{<br>    public string ConnectionString { get; set; } = string.Empty;<br>    public string StartupQueue { get; set; } = string.Empty;<br>    public bool HangfireShouldStart { get; set; }<br>    public string TimeZoneId { get; set; } = &quot;Europe/Istanbul&quot;;<br>    public TimeSpan StaleRunningFlagAfter { get; set; } = TimeSpan.FromHours(1);<br>    public List&lt;HangfireJob&gt; RecurringJobs { get; set; } = new();<br>}<br><br>public class HangfireJob<br>{<br>    public string RecurringJobName { get; set; } = string.Empty;<br>    public string JobClassType { get; set; } = string.Empty;<br>    public string MethodName { get; set; } = string.Empty;<br>    public string CronExpression { get; set; } = string.Empty;<br>    public bool ShouldRegisterJob { get; set; }<br>}</pre><pre>{<br>  &quot;HangfireSettings&quot;: {<br>    &quot;StartupQueue&quot;: &quot;myapp_prod&quot;,<br>    &quot;HangfireShouldStart&quot;: true,<br>    &quot;TimeZoneId&quot;: &quot;Europe/Istanbul&quot;,<br>    &quot;StaleRunningFlagAfter&quot;: &quot;01:00:00&quot;,<br>    &quot;RecurringJobs&quot;: [<br>      {<br>        &quot;RecurringJobName&quot;: &quot;EmployeeSync&quot;,<br>        &quot;ShouldRegisterJob&quot;: true,<br>        &quot;CronExpression&quot;: &quot;0 7 * * 1-5&quot;,<br>        &quot;JobClassType&quot;: &quot;YourApp.Hangfire.Jobs.EmployeeSyncJob&quot;,<br>        &quot;MethodName&quot;: &quot;Execute&quot;<br>      },<br>      {<br>        &quot;RecurringJobName&quot;: &quot;WeeklySurveyAnswers&quot;,<br>        &quot;ShouldRegisterJob&quot;: true,<br>        &quot;CronExpression&quot;: &quot;0 9 * * 0&quot;,<br>        &quot;JobClassType&quot;: &quot;YourApp.Hangfire.Jobs.SurveyAnswersJob&quot;,<br>        &quot;MethodName&quot;: &quot;Execute&quot;<br>      },<br>      {<br>        &quot;RecurringJobName&quot;: &quot;LegacyImport&quot;,<br>        &quot;ShouldRegisterJob&quot;: false,<br>        &quot;CronExpression&quot;: &quot;0 3 * * *&quot;,<br>        &quot;JobClassType&quot;: &quot;YourApp.Hangfire.Jobs.LegacyImportJob&quot;,<br>        &quot;MethodName&quot;: &quot;Execute&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>At startup, the worker makes Hangfire’s recurring-job list match this file. Enabled jobs are added or updated. Everything else with this environment’s prefix is removed, whether it was disabled with ShouldRegisterJob: false or deleted from the file entirely:</p><pre>public class RecurringJobRegistrar<br>{<br>    private readonly IRecurringJobManager _recurringJobManager;<br>    private readonly JobStorage _storage;<br>    private readonly ILogger&lt;RecurringJobRegistrar&gt; _logger;<br>    private readonly string _jobIdPrefix;<br>    public RecurringJobRegistrar(IRecurringJobManager recurringJobManager, JobStorage storage,<br>        IHostEnvironment environment, ILogger&lt;RecurringJobRegistrar&gt; logger)<br>    {<br>        _recurringJobManager = recurringJobManager;<br>        _storage = storage;<br>        _logger = logger;<br>        _jobIdPrefix = $&quot;{environment.EnvironmentName}_&quot;;<br>    }<br><br>    public void RegisterJobs(HangfireSettings settings)<br>    {<br>        var timeZone = TimeZoneInfo.FindSystemTimeZoneById(settings.TimeZoneId);<br>        var registered = new HashSet&lt;string&gt;();<br>        foreach (var jobConfig in settings.RecurringJobs.Where(j =&gt; j.ShouldRegisterJob))<br>        {<br>            string jobId = _jobIdPrefix + jobConfig.RecurringJobName;<br>            var jobType = ResolveJobType(jobConfig.JobClassType);<br>#pragma warning disable CS0618 // QueueName is obsolete; see &quot;Verify queue routing&quot; below<br>            var options = new RecurringJobOptions { TimeZone = timeZone, QueueName = settings.StartupQueue };<br>#pragma warning restore CS0618<br>            _recurringJobManager.AddOrUpdate&lt;JobWrapper&gt;(<br>                jobId,<br>                w =&gt; w.Execute(jobConfig.RecurringJobName, jobType.AssemblyQualifiedName!,<br>                    jobConfig.MethodName, JobCancellationToken.Null),<br>                jobConfig.CronExpression,<br>                options);<br>            registered.Add(jobId);<br>            _logger.LogInformation(&quot;Registered recurring job {JobId} ({Cron})&quot;, jobId, jobConfig.CronExpression);<br>        }<br>        using var connection = _storage.GetConnection();<br><br>        foreach (var existing in connection.GetRecurringJobs())<br>        {<br>            if (existing.Id.StartsWith(_jobIdPrefix, StringComparison.Ordinal) &amp;&amp; !registered.Contains(existing.Id))<br>            {<br>                _recurringJobManager.RemoveIfExists(existing.Id);<br>                _logger.LogInformation(&quot;Removed recurring job {JobId}&quot;, existing.Id);<br>            }<br>        }<br>    }<br><br>    private static Type ResolveJobType(string typeName)<br>    {<br>        var type = typeof(JobWrapper).Assembly.GetType(typeName, throwOnError: false);<br>        if (type is null || type.Namespace != &quot;YourApp.Hangfire.Jobs&quot;)<br>            throw new InvalidOperationException($&quot;&#39;{typeName}&#39; is not a known job type.&quot;);<br>        return type;<br>    }<br>}</pre><p>A few decisions in this code are worth explaining:</p><ul><li><strong>Hangfire is accessed through DI, not static APIs.</strong> IRecurringJobManager and JobStorage come from the container. With Hangfire.AspNetCore, JobStorage.Current is set lazily, so code that runs before the server or dashboard has resolved the storage can find it uninitialized.</li><li><strong>Type lookup is restricted to the worker assembly and the jobs namespace.</strong> A class name in configuration should not be able to instantiate an arbitrary type.</li><li><strong>An unknown type stops startup.</strong> The other option is to log a warning and skip the job, but then a typo in JSON quietly removes a job from production. Failing fast is louder, and it is easier to notice.</li><li><strong>The time zone is configurable.</strong> &quot;Turkey Standard Time&quot; is a Windows ID. &quot;Europe/Istanbul&quot; is the IANA ID. .NET 6+ can convert between the two when ICU is available, but it is better not to depend on that inside a container.</li></ul><h3>Environment-prefixed job IDs and shared storage</h3><p>Job IDs look like Production_EmployeeSync and Test_EmployeeSync, because our environments share one Hangfire database.</p><p>Be careful with this setup. Every Hangfire server runs the recurring-job scheduler for <strong>all</strong> recurring jobs in the storage, not only for its own environment. A Test server will happily enqueue the Production jobs. The only thing that keeps environments apart is that each server listens only to its own queue. If queue routing breaks, environments start running each other’s jobs. Hangfire’s documentation recommends separate storage per environment, and if you can afford that, it is the safer choice.</p><h3>What “no deployment” really means</h3><p>Changing a schedule is now a configuration edit and a worker restart. It is not a code change, but it is still a change to production. If someone edits appsettings.Production.json directly on the server, the running config drifts from source control. We keep the JSON in the repository and deploy configuration through the pipeline like everything else. That pipeline run takes a few minutes, compared to a full build and release for a code change.</p><p>If you need changes without a restart, bind the settings with IOptionsMonitor&lt;HangfireSettings&gt; and call RegisterJobs from its OnChange callback. We haven&#39;t needed this.</p><h3>3. Executing a Job by Name</h3><p>Hangfire normally stores a job as a method call expression. Because our class and method names are strings, we register a single stable entry point, JobWrapper.Execute, and it resolves the real job when it runs:</p><pre>public class JobWrapper<br>{<br>    private readonly IServiceProvider _serviceProvider;<br><br>    public JobWrapper(IServiceProvider serviceProvider) =&gt; _serviceProvider = serviceProvider;<br><br>    [AutomaticRetry(Attempts = 3)]<br>    [DisplayName(&quot;{0}&quot;)]<br>    public async Task Execute(string jobName, string jobTypeName, string methodName,<br>        IJobCancellationToken cancellationToken)<br>    {<br>        var jobType = Type.GetType(jobTypeName)<br>            ?? throw new InvalidOperationException($&quot;Job type not found: {jobTypeName}&quot;);<br>        var method = jobType.GetMethod(methodName)<br>            ?? throw new InvalidOperationException($&quot;Method {methodName} not found on {jobType.Name}&quot;);<br>        var instance = ActivatorUtilities.CreateInstance(_serviceProvider, jobType);<br>        var parameters = method.GetParameters();<br>        object?[]? args = parameters.Length == 1 &amp;&amp; parameters[0].ParameterType == typeof(CancellationToken)<br>            ? new object?[] { cancellationToken.ShutdownToken }<br>            : null;<br>        object? result;<br>        try<br>        {<br>            result = method.Invoke(instance, args);<br>        }<br>        catch (TargetInvocationException ex) when (ex.InnerException is not null)<br>        {<br>            ExceptionDispatchInfo.Throw(ex.InnerException);<br>            throw;<br>        }<br>        if (result is Task task)<br>            await task;<br>    }<br>}</pre><p>Notes on the details:</p><ul><li><strong>DI scope.</strong> With Hangfire.AspNetCore, Hangfire already creates a DI scope for each job execution. The IServiceProvider injected into JobWrapper belongs to that scope, so DbContext and other scoped services get the correct lifetime without creating another scope.</li><li><strong>Missing methods throw.</strong> If the method cannot be found, the job fails. It does not return early. A job that ends as “Succeeded” without doing anything is worse than a failed one, because nobody looks at it.</li><li><strong>The real exception is rethrown.</strong> Without this, synchronous exceptions show up in the dashboard wrapped in TargetInvocationException.</li><li><strong>[DisplayName(&quot;{0}&quot;)]</strong> makes the dashboard show EmployeeSync instead of listing every job as JobWrapper.Execute.</li><li><strong>Cancellation.</strong> ShutdownToken is cancelled when the server stops, and also when the job is deleted from the dashboard (the server checks every CancellationCheckInterval). Because it is passed through, HttpClient and EF Core calls stop instead of running past shutdown.</li></ul><p>As a result, job classes do not depend on Hangfire:</p><pre>public class EmployeeSyncJob<br>{<br>    private readonly IMetadataService _metadataService;<br>    public EmployeeSyncJob(IMetadataService metadataService) =&gt; _metadataService = metadataService;<br>    public Task Execute(CancellationToken cancellationToken = default)<br>        =&gt; _metadataService.SetEmployeeAsync(cancellationToken);<br>}</pre><p><strong>You don’t strictly need a wrapper.</strong> Hangfire can register a Job built from a MethodInfo:</p><pre>var method = jobType.GetMethod(jobConfig.MethodName)!;<br>var job = new Job(jobType, method, CancellationToken.None);<br>recurringJobManager.AddOrUpdate(jobId, job, jobConfig.CronExpression, options);</pre><p>This stores the real type and method in Hangfire, so the dashboard shows them without extra work, and Hangfire replaces the CancellationToken argument itself. We kept the wrapper because it gives us one place for logging, metrics, and the exception handling above. The wrapper does not protect you from renames, though: the type name is still stored as a job argument, and renaming a class still breaks scheduled instances. The only difference is that it fails at run time instead of when Hangfire deserializes the job.</p><h3>4. Skipping Overlapping Runs</h3><h3>What [DisableConcurrentExecution] does</h3><p>Hangfire’s built-in [DisableConcurrentExecution(timeoutInSeconds)] takes a distributed lock around the job&#39;s execution. If another instance holds the lock, the worker <strong>blocks</strong> until the lock is released or the timeout expires. When the timeout expires, it throws DistributedLockTimeoutException. The job fails, and AutomaticRetry schedules it again.</p><p>This guarantees mutual exclusion, and for many jobs that is exactly what you want. It is a poor fit for recurring jobs that sometimes run longer than their interval:</p><pre>Interval: every 5 minutes. Actual run time: 8 minutes.</pre><pre>T+00  A starts and takes the lock.<br>T+05  B is enqueued. A worker picks it up and blocks on the lock.<br>T+08  A finishes. B starts, 3 minutes late.<br>T+10  C is enqueued. Another worker blocks.<br>T+16  B finishes. C starts, 6 minutes late.<br>...   Each run starts later than the last. A worker is always parked on the lock.</pre><p>The jobs can never catch up. Blocked workers sit idle, and with several such jobs a 20-worker pool can run short. If the lock timeout is shorter than the wait, those runs show up as failures and are retried later, which adds more load.</p><p>For a sync job, we don’t want the next run to wait. If the previous run is still working, the next trigger has nothing to add, so we skip it.</p><h3>Cancelling at creation time</h3><p>Hangfire client filters run before a background job is written to storage. Setting context.Canceled = true in IClientFilter.OnCreating means the job is never created: no queue entry, no worker, nothing in the dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZ9sVsnlh23pZOTDx-Widg.png" /></figure><p>The filter needs to know whether a previous instance is still running. It keeps that state as two extra fields in Hangfire’s own recurring-job:{id} hash: Running and LastExecutionStarted. It updates them from IApplyStateFilter, which runs on every state transition:</p><pre>public class SkipWhenPreviousJobIsRunningAttribute : JobFilterAttribute,<br>    IClientFilter, IApplyStateFilter<br>{<br>    private readonly ILogger&lt;SkipWhenPreviousJobIsRunningAttribute&gt; _logger;<br>    private readonly TimeSpan _staleAfter;<br><br>    public SkipWhenPreviousJobIsRunningAttribute(<br>        ILogger&lt;SkipWhenPreviousJobIsRunningAttribute&gt; logger, TimeSpan staleAfter)<br>    {<br>        _logger = logger;<br>        _staleAfter = staleAfter;<br>    }<br><br>    public void OnCreating(CreatingContext context)<br>    {<br>        if (context.Connection is not JobStorageConnection connection) return;<br>        if (!context.Parameters.TryGetValue(&quot;RecurringJobId&quot;, out var param)) return;<br>        if (param is not string recurringJobId || string.IsNullOrWhiteSpace(recurringJobId)) return;<br>        string hashKey = $&quot;recurring-job:{recurringJobId}&quot;;<br>        var running = connection.GetValueFromHash(hashKey, &quot;Running&quot;);<br>        if (!&quot;yes&quot;.Equals(running, StringComparison.OrdinalIgnoreCase)) return;<br>        var lastStartedStr = connection.GetValueFromHash(hashKey, &quot;LastExecutionStarted&quot;);<br>        if (DateTime.TryParse(lastStartedStr, null, DateTimeStyles.RoundtripKind, out var lastStarted)<br>            &amp;&amp; DateTime.UtcNow - lastStarted &gt;= _staleAfter)<br>        {<br>            _logger.LogWarning(&quot;Running flag for {JobId} is older than {StaleAfter}; treating it as stale&quot;,<br>                recurringJobId, _staleAfter);<br>            return;<br>        }<br>        context.Canceled = true;<br>        _logger.LogInformation(&quot;Skipping {JobId}: previous execution still in progress&quot;, recurringJobId);<br>    }<br><br>    public void OnCreated(CreatedContext context) { }<br><br>    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)<br>    {<br>        if (context.NewState is EnqueuedState or ProcessingState)<br>            SetFlag(context, transaction, &quot;yes&quot;);<br>        else if (context.NewState.IsFinal || context.NewState is FailedState)<br>            SetFlag(context, transaction, &quot;no&quot;);<br>    }<br><br>    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction) { }<br><br>    private static void SetFlag(ApplyStateContext context, IWriteOnlyTransaction transaction, string value)<br>    {<br>        if (context.Connection is not JobStorageConnection connection) return;<br>        var recurringJobId = context.GetJobParameter&lt;string&gt;(&quot;RecurringJobId&quot;, allowStale: true);<br>        if (string.IsNullOrWhiteSpace(recurringJobId)) return;<br>        string hashKey = $&quot;recurring-job:{recurringJobId}&quot;;<br>        // Writing to the hash of a deleted recurring job would recreate a broken entry.<br>        if (string.IsNullOrEmpty(connection.GetValueFromHash(hashKey, &quot;Job&quot;))) return;<br>        var fields = new List&lt;KeyValuePair&lt;string, string&gt;&gt; { new(&quot;Running&quot;, value) };<br>        if (value == &quot;yes&quot;)<br>            fields.Add(new(&quot;LastExecutionStarted&quot;, DateTime.UtcNow.ToString(&quot;O&quot;)));<br>        transaction.SetRangeInHash(hashKey, fields);<br>    }<br>}</pre><p>We register the filter globally with the AddHangfire((provider, config) =&gt; ...) overload from Hangfire.AspNetCore, so its logger comes from the real service provider rather than a second container built with BuildServiceProvider().</p><p>The flag is written in the same transaction as the state change, so it cannot get out of sync with a successful transition. Here is how it behaves in the less obvious cases:</p><ul><li><strong>Retries.</strong> With AutomaticRetry, a failing job never actually enters FailedState while it has attempts left; the retry filter replaces it with ScheduledState. The flag therefore stays yes while a retry is pending, and new triggers are skipped until the retries succeed or run out. We want that: a retry and a fresh run of the same sync should not overlap. This only holds while the retry backoff stays below the stale threshold. The stale check compares against the start of the last attempt, and Hangfire’s default backoff reaches about 40 minutes before the eighth attempt and over an hour before the ninth. We cap retries with [AutomaticRetry(Attempts = 3)] on JobWrapper.Execute, which applies to every recurring job and keeps the total backoff under two minutes.</li><li><strong>Deleted jobs.</strong> DeletedState is final, so deleting a job from the dashboard clears the flag.</li><li><strong>Manual triggers.</strong> “Trigger now” in the dashboard goes through the same filter. If the flag is set, the manual run is skipped too, and only the log says so.</li></ul><h3>Limitations of this approach</h3><ul><li><strong>The stale threshold must be longer than your longest legitimate run.</strong> If a job sometimes runs for 90 minutes and the threshold is one hour, overlaps will happen again. We made the threshold configurable for this reason. A per-job value would be even better.</li><li><strong>The check and the flag update are not atomic.</strong> In practice the recurring scheduler creates these jobs one at a time, so this hasn’t caused problems for us. If you need strict mutual exclusion, use a lock and not a flag.</li><li><strong>It relies on Hangfire’s storage layout.</strong> Writing custom fields into recurring-job:{id} works with Hangfire 1.8 and SQL Server storage, but it is not a documented extension point. Re-test it when you upgrade.</li><li><strong>Alternatives exist.</strong> [DisableConcurrentExecution(0)] combined with [AutomaticRetry(Attempts = 0)] gives you &quot;fail immediately when busy&quot;, at the cost of a dashboard full of failed jobs. Hangfire Ace&#39;s Throttling package provides mutexes as a supported feature.</li></ul><h3>5. Recovering From Crashes</h3><p>If the process is killed during a run (OOM, forced container restart), the job is not lost. With SQL Server storage, another worker fetches it again once its invisibility timeout expires, and it eventually reaches a final state that clears the flag. The flag can still end up orphaned when a background job leaves storage without passing through Hangfire’s state machine, for example when it is deleted directly from the database.</p><p>The stale check in OnCreating already covers most cases. For a daily job, the flag is hours old by the next trigger, so the run goes ahead. The gap is <strong>frequent jobs</strong>: with a 5-minute interval and a one-hour threshold, an orphaned flag blocks the job for up to an hour.</p><p>A startup sweep closes that gap. It lives in RecurringJobRegistrar next to RegisterJobs, and it clears the flag for every recurring job that has no live background job, meaning nothing processing on any server, nothing waiting in our queue, and no retry scheduled for later:</p><pre>public void ResetOrphanedRunningFlags(string queue)<br>{<br>    var monitoring = _storage.GetMonitoringApi();<br>    using var connection = _storage.GetConnection();<br><br>    var liveBackgroundJobIds = monitoring.ProcessingJobs(0, int.MaxValue).Select(j =&gt; j.Key)<br>        .Concat(monitoring.EnqueuedJobs(queue, 0, int.MaxValue).Select(j =&gt; j.Key))<br>        .Concat(monitoring.ScheduledJobs(0, int.MaxValue).Select(j =&gt; j.Key));<br>    // Raw job parameters are stored JSON-serialized.<br>    var liveRecurringJobIds = liveBackgroundJobIds<br>        .Select(id =&gt; connection.GetJobParameter(id, &quot;RecurringJobId&quot;))<br>        .Where(raw =&gt; !string.IsNullOrEmpty(raw))<br>        .Select(raw =&gt; SerializationHelper.Deserialize&lt;string&gt;(raw))<br>        .ToHashSet();<br>    foreach (var job in connection.GetRecurringJobs())<br>    {<br>        if (!job.Id.StartsWith(_jobIdPrefix, StringComparison.Ordinal)) continue;<br>        if (liveRecurringJobIds.Contains(job.Id)) continue;<br>        connection.SetRangeInHash($&quot;recurring-job:{job.Id}&quot;,<br>            [new KeyValuePair&lt;string, string&gt;(&quot;Running&quot;, &quot;no&quot;)]);<br>        _logger.LogInformation(&quot;Reset orphaned Running flag for {JobId}&quot;, job.Id);<br>    }<br>}</pre><p>Two details here are easy to get wrong:</p><ul><li><strong>Background job IDs are not recurring job IDs.</strong> ProcessingJobs returns background job IDs (&quot;48213&quot;), not Production_EmployeeSync. A direct comparison never matches, so the sweep would reset every flag, including those of jobs that are actually running. Each background job has to be mapped back to its recurring job through the RecurringJobId parameter.</li><li><strong>It must finish before registration and before the server starts.</strong> Starting it with an unawaited Task.Run would let it race with jobs that are already starting, and any exception it threw would never be observed.</li></ul><p>The startup order in Program.cs:</p><pre>var app = builder.Build();<br><br>if (settings.HangfireShouldStart)<br>{<br>    var registrar = app.Services.GetRequiredService&lt;RecurringJobRegistrar&gt;();<br>    registrar.ResetOrphanedRunningFlags(settings.StartupQueue);<br>    registrar.RegisterJobs(settings);<br>    app.UseAuthentication();<br>    app.UseAuthorization();<br>    app.MapHangfireDashboard(&quot;/hangfire&quot;, new DashboardOptions { Authorization = [] })<br>        .RequireAuthorization(&quot;HangfireDashboard&quot;);<br>}<br>app.MapHealthChecks(&quot;/health&quot;);<br>app.Run();</pre><p>The Hangfire server is a hosted service (AddHangfireServer, also registered only when HangfireShouldStart is true), so it only starts processing in app.Run(), after the sweep and registration have finished. The dashboard can trigger and delete jobs, so it sits behind a normal ASP.NET Core authorization policy. Authorization = [] turns off Hangfire&#39;s default local-requests-only filter, so the policy is the only check.</p><h3>6. Smaller Pitfalls</h3><p><strong>Put schedule rules in the cron expression, not in the job body.</strong></p><pre>// The dashboard shows &quot;Succeeded&quot; on weekends, but nothing ran<br>public async Task Execute(CancellationToken ct)<br>{<br>    if (DateTime.Now.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday)<br>        return;<br>    await _service.RunAsync(ct);<br>}</pre><p>0 7 * * 1-5 expresses the same rule, and the dashboard then shows the job&#39;s real history.</p><p><strong>Verify queue routing instead of assuming it.</strong> In Hangfire 1.8, RecurringJobOptions.QueueName is marked obsolete in favor of AddOrUpdate overloads that take an explicit queue argument. Whichever you use, check the queue column in the dashboard after a deployment. With shared storage, the queue is what keeps environments apart (see section 2). If you keep QueueName, suppress CS0618 locally at that call so the warning doesn&#39;t train people to ignore warnings.</p><p><strong>Don’t fire and forget from startup or jobs.</strong></p><pre>_ = Task.Run(() =&gt; CleanupAsync());</pre><p>Exceptions from this task are never observed, and nothing waits for it to finish. Await it. If it really should run in the background, enqueue it as a Hangfire job so that it gets retries and shows up in the dashboard.</p><h3>7. Was It Worth It?</h3><p>For our use case, yes:</p><ul><li><strong>Schedule changes are a small config change.</strong> They go through the same review and pipeline as any configuration, but no code release is needed. This mattered most when an upstream API had problems and we needed to move or pause a job quickly.</li><li><strong>Overlapping triggers don’t pile up.</strong> If a run is still going, the next trigger is skipped. Workers don’t block on locks, and the queue doesn’t grow.</li><li><strong>Crashes don’t leave jobs stuck.</strong> The stale check and the startup sweep together mean that a killed process doesn’t permanently block the next run.</li></ul><p>What it costs:</p><ul><li>Job wiring moves from compile time to startup, so a typo in JSON only shows up when the worker starts. Failing fast on unknown types keeps that from going unnoticed.</li><li>The skip filter uses an implementation detail of Hangfire’s storage, and its stale threshold has to be tuned together with the retry policy.</li><li>Sharing one Hangfire database across environments depends on queue isolation being correct.</li></ul><p>If you have two jobs and their schedules never change, RecurringJob.AddOrUpdate in Program.cs is simpler and probably enough. These patterns started to pay off once we had several jobs, several environments, and schedules that changed more often than our release cycle.</p><p><strong>Stack</strong>: .NET 8 · Hangfire 1.8 · SQL Server storage</p><p><em>A longer version of this post, including how the filter is registered through DI and how HTTP retries interact with Hangfire’s own retries, is on </em><a href="https://mehmetcanakay.com/"><em>my blog</em></a><em>.</em></p><p>Update (Oct 2026): A reader pointed out that the startup sweep ignored scheduled retries, so a restart during backoff could let a new run overlap a pending retry. The sweep now treats scheduled jobs as live, and section 4 explains how the retry policy and the stale threshold depend on each other. Thanks for the careful read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f93f358ca57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elasticsearch Integration with .NET]]></title>
            <link>https://medium.com/@mehmetcan.akay4/elasticsearch-integration-with-net-4831a0f3477e?source=rss-3e6aaab1d2e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4831a0f3477e</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[ilm]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[log-management]]></category>
            <dc:creator><![CDATA[Mehmet Can Akay]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 13:42:31 GMT</pubDate>
            <atom:updated>2025-02-26T13:42:31.778Z</atom:updated>
            <content:encoded><![CDATA[<h3>Elasticsearch Integration with .NET : Efficient Log Management Using DataStream, Retention Policy and API Key</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsipAEKEuDHKLZi2wTBpFQ.jpeg" /></figure><p>In modern large-scale applications, <strong>log management</strong> is crucial for ensuring system health and performing performance analysis. <strong>Elasticsearch</strong> is a powerful solution for storing, analyzing, and managing log data quickly and efficiently.</p><p>In this article, we will explore <strong>step-by-step .NET integration with Elastic.Clients.Elasticsearch package</strong> and answer the question:<br><strong>How can we implement effective log management using DataStream, Retention Policy, and API Key.</strong></p><ul><li><strong>With DataStream</strong>, we manage logs automatically using <strong>date-based indexing</strong>.</li><li><strong>With Retention Policy</strong>, we <strong>automatically delete old logs after a specific period</strong>, reducing storage costs.</li><li><strong>With API Key authentication</strong>, we ensure a <strong>secure and controlled log recording process</strong>.</li><li><strong>Using the Elastic.Clients.Elasticsearch library in .NET</strong>, we integrate logging seamlessly into Elasticsearch.</li></ul><p>After reading this article, you will be able to <strong>efficiently manage log data in your .NET projects using Elasticsearch</strong>.</p><h3>What is Retention Policy? Why is It Important?</h3><p>A <strong>Retention Policy</strong> in Elasticsearch is a <strong>lifecycle policy that automatically deletes or archives data after a specified time</strong>. In systems dealing with large datasets, it is essential for managing disk usage and maintaining performance.</p><p>Since log data continuously grows, <strong>setting a retention period for old logs</strong> helps prevent unnecessary disk consumption. This leads to:</p><ul><li><strong>Lower storage costs</strong></li><li><strong>Faster search queries</strong></li><li><strong>Quicker access to relevant data</strong></li></ul><p>In Elasticsearch, retention policy is managed using <strong>Index Lifecycle Management (ILM)</strong> policies. ILM allows indices to transition into different phases such as <strong>hot, warm, cold, frozen</strong>, or be <strong>completely deleted</strong> after a certain period.</p><h3>1. Implementing Retention Policy</h3><p>Retention policies allow <strong>old data to be automatically deleted or moved to cold storage</strong> after a set period.</p><p>For example, to <strong>store log data for 30 days and then delete it</strong>, we can define the following ILM policy:</p><pre>PUT _ilm/policy/index-retention-policy<br>{<br>  &quot;policy&quot;: {<br>    &quot;phases&quot;: {<br>      &quot;hot&quot;: {<br>        &quot;actions&quot;: {<br>          &quot;rollover&quot;: {<br>            &quot;max_size&quot;: &quot;50gb&quot;,<br>            &quot;max_age&quot;: &quot;7d&quot;<br>          }<br>        }<br>      },<br>      &quot;delete&quot;: {<br>        &quot;min_age&quot;: &quot;30d&quot;,<br>        &quot;actions&quot;: {<br>          &quot;delete&quot;: {}<br>        }<br>      }<br>    }<br>  }<br>}</pre><h3>How It Works:</h3><ul><li><strong>Hot Phase:</strong> Creates a new index <strong>every 7 days or when the index size reaches 50GB</strong>.</li><li><strong>Delete Phase:</strong> <strong>Deletes indices older than 30 days</strong> automatically.</li></ul><h3>2. Creating Indices Using DataStream</h3><p>To use retention policy effectively, we define a <strong>DataStream</strong> via an index template:</p><pre>PUT _index_template/crm-template<br>{<br>  &quot;index_patterns&quot;: [&quot;crm-*&quot;], <br>  &quot;template&quot;: {<br>    &quot;settings&quot;: {<br>      &quot;index.lifecycle.name&quot;: &quot;index-retention-policy&quot;<br>    },<br>    &quot;mappings&quot;: {<br>      &quot;properties&quot;: {<br>        &quot;@timestamp&quot;: { &quot;type&quot;: &quot;date&quot; },<br>        &quot;LogLevel&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>        &quot;RequestMessage&quot;: { &quot;type&quot;: &quot;text&quot; },<br>        &quot;ResponseMessage&quot;: { &quot;type&quot;: &quot;text&quot; }      <br>      }<br>    }<br>  },<br>  &quot;data_stream&quot;: {}<br>}</pre><h3>Step 3: Creating a DataStream</h3><p>Once the <strong>index template</strong> is defined, we create a <strong>DataStream</strong> using the following command:</p><pre>PUT /_data_stream/crm-ds</pre><h3>3.1 Using DataStream with Date-Formatted Indices and Integrating Retention Policy</h3><p>Using <strong>DataStream</strong> in Elasticsearch makes <strong>index management more efficient</strong>. Organizing log data into <strong>date-based indices</strong> enables a more effective use of retention policies.</p><p>This command <strong>creates a DataStream</strong>, enabling <strong>automated index management with date-based logs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmk5HEJH_PnL5kxEL8n-oA.png" /></figure><ul><li><strong>Elastic-indicesName:</strong> Name of the corresponding index, generated in .ds-crm-ds-YYYY.MM.DD-00000X format, where YYYY.MM.DD represents the date.</li><li><strong>Data stream:</strong> Name of the <strong>DataStream</strong> to which this index belongs (in this case, crm-ds).</li><li><strong>Docs count:</strong> Number of log entries stored in the given date’s index.</li><li><strong>Storage size:</strong> Total disk space occupied by the index.</li></ul><h3>Step 4: Creating a DataView</h3><p>Once we have created our <strong>DataStream and index template</strong>, the next step is to configure <strong>a Data View in Kibana</strong>. A <strong>Data View</strong> allows us to visualize and query our log data effectively in Kibana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTbbVjG24DpiPCki7gojmg.png" /></figure><p>On the right side of the screen, Kibana confirms:</p><ul><li><strong>“Your index pattern matches 1 source.”</strong> — This means the pattern correctly identifies at least one index or DataStream.</li><li><strong>“crm-ds” under Matching Sources</strong> — Confirms that the DataStream (crm-ds) is successfully linked.</li></ul><h3>Step 5: Creating an API Key</h3><p>First, we need to define a <strong>role</strong> that grants <strong>read and write permissions</strong> to the target indices. Run the following command in <strong>Elasticsearch DevTools</strong> or the terminal:</p><pre>PUT _security/role/crmrole<br>{<br>  &quot;indices&quot;: [<br>    {<br>      &quot;names&quot;: [&quot;crm-*&quot;],  <br>      &quot;privileges&quot;: [&quot;read&quot;, &quot;write&quot;]<br>    }<br>  ]<br>}</pre><p>Now, let’s generate an <strong>API Key</strong> for authentication:</p><pre>POST _security/api_key<br>{<br>  &quot;name&quot;: &quot;crm-apikey&quot;,<br>  &quot;role_descriptors&quot;: {<br>    &quot;crmcorerole&quot;: {<br>      &quot;indices&quot;: [<br>        {<br>          &quot;names&quot;: [&quot;crm-*&quot;],<br>          &quot;privileges&quot;: [&quot;read&quot;, &quot;write&quot;]<br>        }<br>      ]<br>    }<br>  }<br>}</pre><p>Elasticsearch returns a <strong>JSON response</strong> containing the API Key. <strong>The </strong><strong>encoded field is crucial for authentication.</strong></p><h3>Step 6: .NET Integration with Elasticsearch</h3><p>To connect Elasticsearch and send log data, we use the <strong>Elastic.Clients.Elasticsearch</strong> library in .NET.</p><h3>6.1 Installing the Required Library</h3><p>Install the package via <strong>NuGet Package Manager</strong>:</p><pre>dotnet add package Elastic.Clients.Elasticsearch</pre><h3>6.2 Establishing a Connection</h3><p>We establish a connection using the <strong>server URL and API Key</strong>:</p><pre>public static void AddElasticSearch(this IServiceCollection services)<br>{<br>    var settings = new ElasticsearchClientSettings(new Uri(ConfigurationHelper.Settings.ElasticSearch.ServerUrl))<br>        .Authentication(new ApiKey(ConfigurationHelper.Settings.ElasticSearch.ApiKey));<br><br>    var elasticClient = new ElasticsearchClient(settings);<br>        services.AddSingleton(elasticClient);<br>}</pre><h3>6.3 Configuration Parameters</h3><p>The following settings should be added to appsettings.json for a successful connection:</p><pre>{<br>  &quot;ElasticSearch&quot;: {<br>    &quot;ServerUrl&quot;:  &quot;https://your-elasticsearch-server-url:9200&quot;,<br>    &quot;ApiKey&quot;:     &quot;your-elasticsearch-api-encoded-key&quot;,<br>    &quot;DataStream&quot;: &quot;datastream-name&quot;<br>  }<br>}</pre><h3>6.4 Sending Logs to Elasticsearch</h3><p>The following method sends logs to Elasticsearch using <strong>DataStream</strong>:</p><pre>public async Task LogAsync(LogLevel logLevel, string requestMessage, <br>                           string responseMessage = null)<br>{<br>    var logEntry = new LogEntry<br>    {<br>        LogLevel = logLevel.ToString().ToUpper(),<br>        RequestMessage = requestMessage,<br>        ResponseMessage = responseMessage ?? string.Empty<br>    };<br><br>    try<br>    {<br>        var response = await _elasticsearchClient.IndexAsync(logEntry, <br>            idx =&gt; idx.Index(ConfigurationHelper.Settings.ElasticSearch.DataStream));<br><br>        if (!response.IsValidResponse)<br>        {<br>            _logger.LogError(&quot;Failed to log to Elasticsearch: {Error}&quot;, response.DebugInformation);<br>        }<br>    }<br>    catch (Exception exception)<br>    {<br>        _logger.LogError(&quot;ElasticSearch log error: {RequestMessage}, {ErrorMessage}&quot;, <br>            requestMessage, exception.Message);<br>    }<br>}</pre><p>This method <strong>automatically sends logs to the correct index using DataStream</strong> and <strong>ensures that logs are retained efficiently using Retention Policy</strong>. 🚀</p><h3>Step:7 Elasticsearch Log Output</h3><p>Once the <strong>.NET application is integrated with Elasticsearch</strong>, logs can be sent and indexed in the configured <strong>DataStream</strong>. The image above represents a <strong>sample log entry stored in Elasticsearch</strong>, displayed in Kibana’s <strong>Discover</strong> section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*rlINyeYXF-j3lNWXVV0C-A.png" /></figure><h3>Conclusion: Efficient Log Management with .NET and Elasticsearch</h3><p>Implementing <strong>Elasticsearch with .NET</strong> enables seamless, scalable, and structured <strong>log management</strong> using <strong>DataStream, Retention Policy and API Key authentication</strong>.</p><ul><li><strong>Automated log indexing</strong> with DataStream for structured storage.</li><li><strong>Efficient retention management</strong> to optimize storage and query performance.</li><li><strong>Secure and controlled access</strong> through API Key authentication.</li><li><strong>Seamless .NET integration</strong> for real-time logging and monitoring.</li></ul><p>By leveraging these features, organizations can ensure <strong>better observability, faster debugging, and cost-effective log retention</strong>, enhancing <strong>system reliability and operational efficiency</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4831a0f3477e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>