Skip to main content

.NET Background Services with IHostedService

Build reliable background services in .NET — long-running workers, scheduled tasks, queue processors, and graceful shutdown handling.

Fill in the placeholders

Edit the values, then copy your finished prompt.

Your Prompt
prompt.txt
Create background services for my .NET 8 application that handles email sending, report generation, and data synchronization. 1) Worker service: implement a BackgroundService that polls an API every 30 seconds and synchronizes data to the local database with proper cancellation token handling, exponential backoff on failures, and health reporting. 2) Scheduled task: create a cron-based (e.g., every day at 2 AM, every hour on weekdays) scheduler using PeriodicTimer with Cronos for cron expression parsing that runs nightly report generation and stale-record cleanup — handle overlapping executions and timezone awareness. 3) Queue processor: build a queue consumer that reads from Azure Service Bus queue and processes OrderPlaced and PaymentReceived events messages with concurrency limit of 5 parallel processors and ordered processing for messages for the same order ID processed in sequence. 4) Graceful shutdown: implement IHostApplicationLifetime hooks that drain in-flight work within 30 seconds timeout, persist incomplete work to a SQL Server table tracking in-flight message state, and resume on restart. 5) Error handling: configure different error strategies — retry with backoff for timeouts and HTTP 503 responses from upstream APIs, dead-letter for malformed payloads and validation failures, and circuit breaker for a third-party email provider API. 6) Health checks: add IHealthCheck implementations that report service status, queue depth, and last successful processing time. 7) Monitoring: emit structured logs and metrics with OpenTelemetry with Application Insights for processing rate, error rate, and queue lag. 8) Testing: write tests that verify the service starts, processes work, handles errors, and shuts down cleanly.

What this prompt does

This prompt builds reliable background services for a [dotnet_version] app handling [service_purposes]. It is structured around the patterns that make background work trustworthy: a BackgroundService doing [worker_task] with backoff, a [schedule_pattern] scheduler using [timer_approach] for [scheduled_task], a queue consumer reading [queue_source] and processing [message_type] at concurrency [concurrency] with ordering for [ordering_requirement], graceful shutdown draining work within [shutdown_timeout] into [recovery_store], error strategies for [transient_errors] and [permanent_errors], health checks, and telemetry via [telemetry_tool].

The variables decide the shape of each worker. [queue_source] and [message_type] define the consumer, [concurrency] and [ordering_requirement] balance throughput against correctness, and [shutdown_timeout] plus [recovery_store] ensure in-flight work survives a deploy. The error-strategy variables split failures into retry, dead-letter, and circuit-breaker paths so transient blips are handled differently from permanent ones. That distinction is what keeps a background service from either dropping real work or looping forever on a poison message, and the circuit breaker around [external_dependency] stops one flaky upstream from taking the whole worker down with it.

When to use it

  • An app needs reliable background work: queue processing, scheduled jobs, or data sync
  • You want graceful shutdown so in-flight work is never silently lost on deploy
  • Building a queue consumer with a concurrency cap and ordered processing where required
  • Adding a [schedule_pattern] scheduler that avoids overlapping executions
  • You need health checks reporting queue depth and last successful processing time
  • Wiring structured logs and metrics through [telemetry_tool]

Example output

Expect several worker implementations: a BackgroundService class with cancellation and backoff, a scheduler using [timer_approach], a queue processor with a SemaphoreSlim-style concurrency limit, IHostApplicationLifetime shutdown hooks persisting to [recovery_store], error-handling branches, IHealthCheck implementations, and telemetry instrumentation. Each comes as focused code plus explanation rather than one combined service.

Pro tips

  • Set [shutdown_timeout] to a value your platform actually allows; Kubernetes SIGTERM-to-SIGKILL windows are finite, so a long drain timeout may be cut off
  • Choose [recovery_store] carefully — persisting in-flight state is what lets a restarted worker resume instead of dropping messages
  • Match [concurrency] to downstream limits; high parallelism against a rate-limited API just shifts the failure to transient errors
  • Keep [ordering_requirement] narrow (for example per order ID) so you don't serialize the whole queue unnecessarily
  • Distinguish [transient_errors] from [permanent_errors] explicitly so retries don't loop forever on a malformed payload
  • Have the health check expose queue depth and last-success time; a worker that is alive but stuck is invisible without it
  • Use exponential backoff on the [worker_task] failure path so a transient outage does not turn into a tight retry loop hammering the upstream API
  • Emit metrics for processing rate and queue lag through [telemetry_tool]; lag trending up is the earliest sign the worker cannot keep pace with incoming volume

Frequently Asked Questions

How does this prevent losing in-flight work on deploy?
It uses IHostApplicationLifetime hooks to drain in-flight work within the `[shutdown_timeout]` and persist anything incomplete to `[recovery_store]`, then resumes on restart. This means a deploy or restart does not silently drop messages that were mid-processing when shutdown began.
Can it enforce ordered processing for some messages but not others?
Yes. The prompt processes messages at a concurrency of `[concurrency]` while keeping `[ordering_requirement]` ordered, for example messages sharing an order ID processed in sequence. This lets you parallelize unrelated work while serializing only the subset that genuinely needs ordering.
What is the difference between the retry and dead-letter strategies?
Retry with backoff handles `[transient_errors]` like timeouts or 503s that are likely to succeed on a second attempt. Dead-lettering handles `[permanent_errors]` such as malformed payloads that will never succeed, so they are set aside for inspection instead of looping forever and blocking the queue.
Why add health checks to a background worker?
A background service can be running yet stuck, with a growing queue and no recent successful processing. Health checks that report status, queue depth, and last successful processing time make that condition visible to your orchestrator and dashboards, so you catch a stalled worker before it backs up badly.
Engr Mejba Ahmed

Need this built for real?

Engr Mejba Ahmed

AI Developer · Software Engineer

I'm Mejba — I design and ship production AI systems, automations, and full-stack apps. If you want this turned into a working solution for your team, let's talk.

More in C# & .NET Prompts

Engr Mejba Ahmed

Engr Mejba Ahmed

AI assistant · trained on my work

👋

Hey there!

Quick Actions

WhatsApp Direct line to me

Chat on WhatsApp

+880 1723 741224 · Replies within the hour on working days

Popular Questions

Engr Mejba Ahmed is connected
Engr Mejba Ahmed is typing...
Engr Mejba Ahmed avatar

✉ Want me to follow up? Drop your email

Engr Mejba Ahmed avatar

📞 Connect Directly

Choose how you'd like to reach me

WhatsApp

+880 1723 741224

Email

mejba.13@gmail.com

✓ Details sent! I'll get back to you shortly.

Powered by Claude

335+

Blog Posts

25

AI Courses

63

Projects

Services & Expertise

Pricing & Process

Learning & Resources

Connect & Support