SlideShare a Scribd company logo
www.seavus.com
With Hangfire
Background Processing
Nov. 2016
Aleksandar Bozinovski
Agenda
• Why background processing
• Options for ASP.NET applications
• Hangfire architecture
• Types of tasks
• IoC Containers
• Hosting
• Dashboard
• Demo
Page 2
Why Background Processing?
• Lengthy operations like updating lot of
records in DB
• Checking every 2 hours for new data or files
• Invoice generation at the end of every billing
period
• Monthly Reporting
• Rebuild data, indexes or search-optimized
index after data change
• Automatic subscription renewal
• Regular Mailings
• Send an email due to an action
• Background service provisioning
Page 3
Types of Background Tasks
• Fire & Forget
• Lengthy operations like updating lot of records in DB
• Send an email due to an action
• Delayed
• Automatic subscription renewal
• Rebuild data, indexes or search-optimized index after data
change
• Periodic & Scheduled
• Checking every 2 hours for new data or files
• Invoice generation at the end of every billing period
• Monthly Reporting
• Regular Mailings
• Background service provisioning
Page 4
Background Processing Must be…
• Reliable
• The task must be executed. Users must gets their emails
even if the network is not available at the moment.
• For some cases, the system must be able to re-execute the
task. The invoice will be generated as soon as the database
is online.
• Main application logic is unaffected of the background
processing issues. Users will submit changes in the system
unaware that we haven’t updated search-optimized index.
• Transparent
• Monitoring. As soon as the database is not accessible, we
need to know.
• How many invoices we have left to be sent?
• Log and audit. What happened with that invoice from last
month?
Page 5
Background Processing Must be…
• Distributed
• Add more processes or servers to increase processing
power.
• Very often required for cloud solutions.
• Resilient
• Servers crash, network fails...
• Should be able to recover after crash.
• Extensible
• Processing logic can be very complex. Processes can depend
on one another.
• Sometimes we have bug in the code. We need to deploy
new version and resume the work.
Page 6
Options We Have
• Threads/TPL
• Difficult to work with
• Nightmare to debug
• Unreliable in ASP.NET
• QueueBackgroundWorkItem
• ASP.NET specific, added in version 4.5.2
• Handles App Pool recycle better than threads or TPL
• Still not reliable
Page 7
HostingEnvironment.QueueBackgroundWorkItem(ct => SendMailAsync(user.Email));
Task.Run(() => SendMailAsync(User.Identity.Name));
Options We Have
• FluentScheduler
• https://github.com/fluentscheduler/FluentScheduler
• Quartz Enterprise Scheduler .NET
• .NET port of the popular Java job scheduling framework
• http://www.quartz-scheduler.net/
Page 8
Schedule<MyTask>().ToRunNow().AndEvery(2).Seconds();
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
)
.Build();
Enter Hangfire
Page 9
• http://hangfire.io/
• First version in 2013
• First stable version in 2014
• Inspired by Sidekiq - https://github.com/mperham/sidekiq
As an ASP.NET developer, Ialways wanted tohave something
simple tohandle scenarios where you need tobuild along-
running async task
But every time Ifaced Windows Services, message queues andother difficult-to-
understand problems andhard-to-maintain solutions, my head exploded intoa
billion pieces. At the same time Ilooked at Rails' Sidekiqandwished tohave a
simple .NET alternative forbackground job processing.
Enter Hangfire
Page 10
Hangfire Architecture
Page 11
• Fire & Forget Jobs
• Delayed Jobs
• Recurrent Jobs
All of them running in
a background thread on
same server or other
one
ASP.NET Thread Pool
safe!
Persisting jobs
Page 12
• Hangfire uses a shared persistent storage
mechanism for ensuring data survives
application restarts.
IoC
Page 13
• Hangfire uses the JobActivator class to instantiate the
target types before invoking instance methods. You can
override its behavior to perform more complex logic on a
type instantiation. For example, you can tell it to use IoC
container that is used in your project:
Launching Tasks
Page 14
Batches – Pro Version
Page 15
Hosting Hangfire – ASP.NET
Page 16
Hosting Hangfire – Console App
Page 17
Hangfire Dashboard
Page 18
• OWIN middleware
• Can be plugged into
• ASP.NET
• ASP.NET MVC
• Nancy
• ServiceStack
• OWIN Self-Host
Hangfire Dashboard Features
Page 19
• Realtime Graph
• Queues
• History and details
• Automatic and manual
retries
Demo
Page 20
Best practices
Page 21
• Job arguments small and simple and serializable
• Job methods should be reentrant and idempotent
public void DoSomething(Entity entity) { } // Not good
public void DoSomething(int entityId) { } // Better
public void SendTheMail() // Not good
{
_emailService.Send("person@exapmle.com", "Hello!");
}
public void SendTheMail(int deliveryId) // Better
{
if (_emailService.IsNotDelivered(deliveryId))
{
_emailService.Send("person@example.com", "Hello!");
_emailService.SetDelivered(deliveryId);
}
}
Best practices
Page 22
• Job methods should be atomic and transactional. This can
be quite a challenge, separate operations often cannot join
in a same transaction.
• Compensation logic.
public void SendTheMail(int deliveryId)
{
if (_emailService.IsNotDelivered(deliveryId))
{
try
{
_emailService.SetDelivered(deliveryId);
_emailService.Send("person@example.com", "Hello!");
}
catch
{
_emailService.SetNotDelivered(deliveryId); // Compensation logic.
throw;
}
}
}
Demo
Page 23
www.seavus.co
Thank You
Ad

More Related Content

What's hot (20)

Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE
Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE
Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE
confluent
 
An introduction to Microservices
An introduction to MicroservicesAn introduction to Microservices
An introduction to Microservices
Cisco DevNet
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
Araf Karsh Hamid
 
CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton
Araf Karsh Hamid
 
CI/CD Overview
CI/CD OverviewCI/CD Overview
CI/CD Overview
An Nguyen
 
Identity and Client Management using OpenID Connect and SAML
Identity and Client Management using OpenID Connect and SAMLIdentity and Client Management using OpenID Connect and SAML
Identity and Client Management using OpenID Connect and SAML
pqrs1234
 
Introduction to Github Actions
Introduction to Github ActionsIntroduction to Github Actions
Introduction to Github Actions
Knoldus Inc.
 
Introduction to CICD
Introduction to CICDIntroduction to CICD
Introduction to CICD
Knoldus Inc.
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Jenkins-CI
Jenkins-CIJenkins-CI
Jenkins-CI
Gong Haibing
 
Stability Patterns for Microservices
Stability Patterns for MicroservicesStability Patterns for Microservices
Stability Patterns for Microservices
pflueras
 
Enterprise Software Architecture styles
Enterprise Software Architecture stylesEnterprise Software Architecture styles
Enterprise Software Architecture styles
Araf Karsh Hamid
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices
Bozhidar Bozhanov
 
우아한 모노리스
우아한 모노리스우아한 모노리스
우아한 모노리스
Arawn Park
 
Apache Kafka
Apache KafkaApache Kafka
Apache Kafka
Diego Pacheco
 
NiFi Developer Guide
NiFi Developer GuideNiFi Developer Guide
NiFi Developer Guide
Deon Huang
 
CICD Pipeline Using Github Actions
CICD Pipeline Using Github ActionsCICD Pipeline Using Github Actions
CICD Pipeline Using Github Actions
Kumar Shìvam
 
Azure API Management
Azure API ManagementAzure API Management
Azure API Management
Daniel Toomey
 
Stream Processing with Apache Kafka and .NET
Stream Processing with Apache Kafka and .NETStream Processing with Apache Kafka and .NET
Stream Processing with Apache Kafka and .NET
confluent
 
Distributed Transaction in Microservice
Distributed Transaction in MicroserviceDistributed Transaction in Microservice
Distributed Transaction in Microservice
Nghia Minh
 
Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE
Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE
Kafka Multi-Tenancy—160 Billion Daily Messages on One Shared Cluster at LINE
confluent
 
An introduction to Microservices
An introduction to MicroservicesAn introduction to Microservices
An introduction to Microservices
Cisco DevNet
 
CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton CI-CD Jenkins, GitHub Actions, Tekton
CI-CD Jenkins, GitHub Actions, Tekton
Araf Karsh Hamid
 
CI/CD Overview
CI/CD OverviewCI/CD Overview
CI/CD Overview
An Nguyen
 
Identity and Client Management using OpenID Connect and SAML
Identity and Client Management using OpenID Connect and SAMLIdentity and Client Management using OpenID Connect and SAML
Identity and Client Management using OpenID Connect and SAML
pqrs1234
 
Introduction to Github Actions
Introduction to Github ActionsIntroduction to Github Actions
Introduction to Github Actions
Knoldus Inc.
 
Introduction to CICD
Introduction to CICDIntroduction to CICD
Introduction to CICD
Knoldus Inc.
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
Haim Michael
 
Stability Patterns for Microservices
Stability Patterns for MicroservicesStability Patterns for Microservices
Stability Patterns for Microservices
pflueras
 
Enterprise Software Architecture styles
Enterprise Software Architecture stylesEnterprise Software Architecture styles
Enterprise Software Architecture styles
Araf Karsh Hamid
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices
Bozhidar Bozhanov
 
우아한 모노리스
우아한 모노리스우아한 모노리스
우아한 모노리스
Arawn Park
 
NiFi Developer Guide
NiFi Developer GuideNiFi Developer Guide
NiFi Developer Guide
Deon Huang
 
CICD Pipeline Using Github Actions
CICD Pipeline Using Github ActionsCICD Pipeline Using Github Actions
CICD Pipeline Using Github Actions
Kumar Shìvam
 
Azure API Management
Azure API ManagementAzure API Management
Azure API Management
Daniel Toomey
 
Stream Processing with Apache Kafka and .NET
Stream Processing with Apache Kafka and .NETStream Processing with Apache Kafka and .NET
Stream Processing with Apache Kafka and .NET
confluent
 
Distributed Transaction in Microservice
Distributed Transaction in MicroserviceDistributed Transaction in Microservice
Distributed Transaction in Microservice
Nghia Minh
 

Similar to Background processing with hangfire (20)

The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
12-Step Program for Scaling Web Applications on PostgreSQL
12-Step Program for Scaling Web Applications on PostgreSQL12-Step Program for Scaling Web Applications on PostgreSQL
12-Step Program for Scaling Web Applications on PostgreSQL
Konstantin Gredeskoul
 
Delivering big content at NBC News with RavenDB
Delivering big content at NBC News with RavenDBDelivering big content at NBC News with RavenDB
Delivering big content at NBC News with RavenDB
John Bennett
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
DrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalabilityDrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalability
cherryhillco
 
Custom coded projects
Custom coded projectsCustom coded projects
Custom coded projects
Marko Heijnen
 
Porting ASP.NET applications to Windows Azure
Porting ASP.NET applications to Windows AzurePorting ASP.NET applications to Windows Azure
Porting ASP.NET applications to Windows Azure
Gunnar Peipman
 
SharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi Vončina
SPC Adriatics
 
Benchmarking at Parse
Benchmarking at ParseBenchmarking at Parse
Benchmarking at Parse
Travis Redman
 
Advanced Benchmarking at Parse
Advanced Benchmarking at ParseAdvanced Benchmarking at Parse
Advanced Benchmarking at Parse
MongoDB
 
SharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceSharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 Performance
Brian Culver
 
Realtime traffic analyser
Realtime traffic analyserRealtime traffic analyser
Realtime traffic analyser
Alex Moskvin
 
Cloud computing UNIT 2.1 presentation in
Cloud computing UNIT 2.1 presentation inCloud computing UNIT 2.1 presentation in
Cloud computing UNIT 2.1 presentation in
RahulBhole12
 
Drupal performance
Drupal performanceDrupal performance
Drupal performance
Piyuesh Kumar
 
Building & Testing Scalable Rails Applications
Building & Testing Scalable Rails ApplicationsBuilding & Testing Scalable Rails Applications
Building & Testing Scalable Rails Applications
evilmike
 
SharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceSharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 Performance
Brian Culver
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
Eugene Lazutkin
 
Performance stack
Performance stackPerformance stack
Performance stack
Shayne Bartlett
 
Webinar - DreamObjects/Ceph Case Study
Webinar - DreamObjects/Ceph Case StudyWebinar - DreamObjects/Ceph Case Study
Webinar - DreamObjects/Ceph Case Study
Ceph Community
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
Panagiotis Kanavos
 
12-Step Program for Scaling Web Applications on PostgreSQL
12-Step Program for Scaling Web Applications on PostgreSQL12-Step Program for Scaling Web Applications on PostgreSQL
12-Step Program for Scaling Web Applications on PostgreSQL
Konstantin Gredeskoul
 
Delivering big content at NBC News with RavenDB
Delivering big content at NBC News with RavenDBDelivering big content at NBC News with RavenDB
Delivering big content at NBC News with RavenDB
John Bennett
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (Greek)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (Greek)
Panagiotis Kanavos
 
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)Parallel and Asynchronous Programming -  ITProDevConnections 2012 (English)
Parallel and Asynchronous Programming - ITProDevConnections 2012 (English)
Panagiotis Kanavos
 
DrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalabilityDrupalCampLA 2014 - Drupal backend performance and scalability
DrupalCampLA 2014 - Drupal backend performance and scalability
cherryhillco
 
Custom coded projects
Custom coded projectsCustom coded projects
Custom coded projects
Marko Heijnen
 
Porting ASP.NET applications to Windows Azure
Porting ASP.NET applications to Windows AzurePorting ASP.NET applications to Windows Azure
Porting ASP.NET applications to Windows Azure
Gunnar Peipman
 
SharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi VončinaSharePoint 2013 Performance Analysis - Robi Vončina
SharePoint 2013 Performance Analysis - Robi Vončina
SPC Adriatics
 
Benchmarking at Parse
Benchmarking at ParseBenchmarking at Parse
Benchmarking at Parse
Travis Redman
 
Advanced Benchmarking at Parse
Advanced Benchmarking at ParseAdvanced Benchmarking at Parse
Advanced Benchmarking at Parse
MongoDB
 
SharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceSharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 Performance
Brian Culver
 
Realtime traffic analyser
Realtime traffic analyserRealtime traffic analyser
Realtime traffic analyser
Alex Moskvin
 
Cloud computing UNIT 2.1 presentation in
Cloud computing UNIT 2.1 presentation inCloud computing UNIT 2.1 presentation in
Cloud computing UNIT 2.1 presentation in
RahulBhole12
 
Building & Testing Scalable Rails Applications
Building & Testing Scalable Rails ApplicationsBuilding & Testing Scalable Rails Applications
Building & Testing Scalable Rails Applications
evilmike
 
SharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceSharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 Performance
Brian Culver
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
Eugene Lazutkin
 
Webinar - DreamObjects/Ceph Case Study
Webinar - DreamObjects/Ceph Case StudyWebinar - DreamObjects/Ceph Case Study
Webinar - DreamObjects/Ceph Case Study
Ceph Community
 
Ad

Recently uploaded (20)

Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Ad

Background processing with hangfire

  • 2. Agenda • Why background processing • Options for ASP.NET applications • Hangfire architecture • Types of tasks • IoC Containers • Hosting • Dashboard • Demo Page 2
  • 3. Why Background Processing? • Lengthy operations like updating lot of records in DB • Checking every 2 hours for new data or files • Invoice generation at the end of every billing period • Monthly Reporting • Rebuild data, indexes or search-optimized index after data change • Automatic subscription renewal • Regular Mailings • Send an email due to an action • Background service provisioning Page 3
  • 4. Types of Background Tasks • Fire & Forget • Lengthy operations like updating lot of records in DB • Send an email due to an action • Delayed • Automatic subscription renewal • Rebuild data, indexes or search-optimized index after data change • Periodic & Scheduled • Checking every 2 hours for new data or files • Invoice generation at the end of every billing period • Monthly Reporting • Regular Mailings • Background service provisioning Page 4
  • 5. Background Processing Must be… • Reliable • The task must be executed. Users must gets their emails even if the network is not available at the moment. • For some cases, the system must be able to re-execute the task. The invoice will be generated as soon as the database is online. • Main application logic is unaffected of the background processing issues. Users will submit changes in the system unaware that we haven’t updated search-optimized index. • Transparent • Monitoring. As soon as the database is not accessible, we need to know. • How many invoices we have left to be sent? • Log and audit. What happened with that invoice from last month? Page 5
  • 6. Background Processing Must be… • Distributed • Add more processes or servers to increase processing power. • Very often required for cloud solutions. • Resilient • Servers crash, network fails... • Should be able to recover after crash. • Extensible • Processing logic can be very complex. Processes can depend on one another. • Sometimes we have bug in the code. We need to deploy new version and resume the work. Page 6
  • 7. Options We Have • Threads/TPL • Difficult to work with • Nightmare to debug • Unreliable in ASP.NET • QueueBackgroundWorkItem • ASP.NET specific, added in version 4.5.2 • Handles App Pool recycle better than threads or TPL • Still not reliable Page 7 HostingEnvironment.QueueBackgroundWorkItem(ct => SendMailAsync(user.Email)); Task.Run(() => SendMailAsync(User.Identity.Name));
  • 8. Options We Have • FluentScheduler • https://github.com/fluentscheduler/FluentScheduler • Quartz Enterprise Scheduler .NET • .NET port of the popular Java job scheduling framework • http://www.quartz-scheduler.net/ Page 8 Schedule<MyTask>().ToRunNow().AndEvery(2).Seconds(); ITrigger trigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0)) ) .Build();
  • 9. Enter Hangfire Page 9 • http://hangfire.io/ • First version in 2013 • First stable version in 2014 • Inspired by Sidekiq - https://github.com/mperham/sidekiq As an ASP.NET developer, Ialways wanted tohave something simple tohandle scenarios where you need tobuild along- running async task But every time Ifaced Windows Services, message queues andother difficult-to- understand problems andhard-to-maintain solutions, my head exploded intoa billion pieces. At the same time Ilooked at Rails' Sidekiqandwished tohave a simple .NET alternative forbackground job processing.
  • 11. Hangfire Architecture Page 11 • Fire & Forget Jobs • Delayed Jobs • Recurrent Jobs All of them running in a background thread on same server or other one ASP.NET Thread Pool safe!
  • 12. Persisting jobs Page 12 • Hangfire uses a shared persistent storage mechanism for ensuring data survives application restarts.
  • 13. IoC Page 13 • Hangfire uses the JobActivator class to instantiate the target types before invoking instance methods. You can override its behavior to perform more complex logic on a type instantiation. For example, you can tell it to use IoC container that is used in your project:
  • 15. Batches – Pro Version Page 15
  • 16. Hosting Hangfire – ASP.NET Page 16
  • 17. Hosting Hangfire – Console App Page 17
  • 18. Hangfire Dashboard Page 18 • OWIN middleware • Can be plugged into • ASP.NET • ASP.NET MVC • Nancy • ServiceStack • OWIN Self-Host
  • 19. Hangfire Dashboard Features Page 19 • Realtime Graph • Queues • History and details • Automatic and manual retries
  • 21. Best practices Page 21 • Job arguments small and simple and serializable • Job methods should be reentrant and idempotent public void DoSomething(Entity entity) { } // Not good public void DoSomething(int entityId) { } // Better public void SendTheMail() // Not good { _emailService.Send("[email protected]", "Hello!"); } public void SendTheMail(int deliveryId) // Better { if (_emailService.IsNotDelivered(deliveryId)) { _emailService.Send("[email protected]", "Hello!"); _emailService.SetDelivered(deliveryId); } }
  • 22. Best practices Page 22 • Job methods should be atomic and transactional. This can be quite a challenge, separate operations often cannot join in a same transaction. • Compensation logic. public void SendTheMail(int deliveryId) { if (_emailService.IsNotDelivered(deliveryId)) { try { _emailService.SetDelivered(deliveryId); _emailService.Send("[email protected]", "Hello!"); } catch { _emailService.SetNotDelivered(deliveryId); // Compensation logic. throw; } } }

Editor's Notes

  • #13: RDB = Point in time snapshot AOF = Append Only File
  • #22: Idempotence = Operation that can be applied multiple times without changing the result beyond the initial application.  Reentrancy = Subroutine is called reentrant if it can be interrupted in the middle of its execution, and then be safely called again ("re-entered") before its previous invocations complete execution.