HHangfire Handbook

TEMEL

Giriş & Kurulum

Hangfire, .NET uygulamalarında background job processing için açık kaynaklı bir framework'tür. Fire-and-forget, delayed, recurring ve continuation job türlerini persistent storage üzerinde güvenilir şekilde çalıştırır.

Client BackgroundJob.Enqueue() RecurringJob.AddOrUpdate() Storage SQL Server / Redis Job Queue + State Server Worker Threads Job Execution Dashboard Monitoring UI serialize fetch

Karar Rehberi

Durum Öneri Örnek veya gerekçe
E-posta gönderimi Uygun: Fire-and-forget E-ticaret sipariş onayı
Rapor oluşturma Uygun: Delayed/Recurring Günlük satış raporu PDF
Dosya işleme Uygun: Long-running job CSV import (100K satır)
Basit in-memory cache refresh Uygun değil: Overkill Timer/IHostedService yeterli
Sub-millisecond latency Uygun değil: Polling overhead Real-time trading
Distributed event-driven Uygun değil: Mesajlaşma sistemi kullan RabbitMQ/Kafka daha uygun

Hangfire vs IHostedService: Eğer job'larınız uygulama restart'ında kaybolabilir ve persistence gerekmiyorsa, IHostedService daha basit bir çözümdür. Hangfire'ın gücü at-least-once guarantee ve persistent storage ile gelir.

Örnek: Bir e-ticaret platformunda sipariş sonrası fatura PDF oluşturma, kargo entegrasyonu çağırma ve müşteriye e-posta gönderme — üçü de fire-and-forget job olarak enqueue edilir. Kullanıcı anında "Siparişiniz alındı" görür, arka planda işlemler güvenilir şekilde tamamlanır.

Lisans ve Özellik Katmanları

Hangfire'ın özellik katmanları ile satın alma planları aynı şey değildir. Core açık kaynaklı temel üründür; Pro ve Ace ise ücretli planlarla sunulan ek paketlerdir.

Katman Lisans ve erişim Sağladığı özellikler
Core Ücretsiz, LGPL 3.0; ticari kullanım dahil Temel job türleri, dashboard, SQL Server ve In-Memory storage, retry, job filters ve [DisableConcurrentExecution]
Pro Ücretli; Startup ve üzeri planlarla sunulur Batch jobs, batch continuations, Redis storage, performance counters ve Pro paket güncellemeleri
Ace Ücretli; Business ve Enterprise planlarında sunulur [Mutex], [Semaphore] ve fixed, sliding veya dynamic window rate limiting

Lisans notu: Rehberde Pro veya Ace olarak belirtilen özellikler ücretli paket gerektirir. Güncel plan ve fiyatlar için resmi fiyatlandırma sayfasını kontrol edin.

NuGet Paketleri

Paket Amaç Lisans
Hangfire.Core Temel kütüphane (job creation, state machine) Ücretsiz (LGPL)
Hangfire.AspNetCore ASP.NET Core DI + hosted service entegrasyonu Ücretsiz
Hangfire.SqlServer SQL Server storage provider Ücretsiz
Hangfire.InMemory Test/development için in-memory storage Ücretsiz
Hangfire.Pro Batch jobs (BatchJob.StartNew) Pro
Hangfire.Pro.Redis Redis storage provider (yüksek throughput) Pro
Hangfire.Throttling Mutex, Semaphore, Rate Limiting Ace

Kurulum

dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer

Minimal Konfigürasyon (Program.cs)

using Hangfire;
using Hangfire.SqlServer;

var builder = WebApplication.CreateBuilder(args);

// Hangfire servislerini kaydet
builder.Services.AddHangfire(config => config
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
    {
        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
        QueuePollInterval = TimeSpan.Zero,              // Long-polling (SlidingInvisibilityTimeout ile birlikte)
        UseRecommendedIsolationLevel = true,
        DisableGlobalLocks = true,                      // Schema 7+ gerektirir (yeni kurulumda otomatik)
        TryAutoDetectSchemaDependentOptions = true,     // 1.8: Schema'ya göre opsiyonları otomatik ayarlar
        SchemaName = "hangfire"
    }));

// Background job server'ı IHostedService olarak ekle
builder.Services.AddHangfireServer(options =>
{
    options.WorkerCount = Environment.ProcessorCount * 5; // Varsayılan (IO-bound iş yükleri için)
    options.Queues = new[] { "critical", "default", "low" };
});

var app = builder.Build();

// Dashboard — development'ta serbest, production'da auth zorunlu
if (app.Environment.IsDevelopment())
{
    app.UseHangfireDashboard("/hangfire");
}
else
{
    app.UseHangfireDashboard("/hangfire", new DashboardOptions
    {
        Authorization = new[] { new HangfireAuthorizationFilter() },
        DisplayStorageConnectionString = false
    });
}

app.Run();

appsettings.json

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=.;Database=HangfireDb;Trusted_Connection=true;TrustServerCertificate=true;"
  }
}

Örnek: İlk kurulumda Hangfire otomatik olarak gerekli tabloları oluşturur (schema migration). Production'da SchemaName parametresi ile kendi schema'nızda izole edebilirsiniz — böylece uygulama tabloları ile karışmaz.

Hangfire 1.7 → 1.8 Migration

// 1.8'e geçerken CompatibilityLevel'ı yükseltin
// Bu, yeni storage optimizasyonlarını aktif eder
builder.Services.AddHangfire(config => config
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage(connectionString));

Dikkat: CompatibilityLevel.Version_180 ayarlandıktan sonra 1.7'ye geri dönüş YAPILAMAZ — yeni state format'ı eski sürümle uyumsuz. Önce tüm node'ları 1.8'e güncelleyin, sonra level'ı yükseltin. Rolling deploy sırasında mixed-version çalışması için level'ı geçici olarak Version_170'de bırakın.