Hangfire Discussion

Hangfire High CPU Usage

queues
recurring
Tags: #<Tag:0x00007f850162d508> #<Tag:0x00007f850162d238>

#1

Hello good day,

I’ve been using hangfire for a while now. I use it in production for recurring jobs and some background jobs.
A new requirement in my application came up, it involves configuring recurring debits for customers on the platform.

I’ve recently run into an issue where when I try to schedule a background job, it eats up all my servers resources (CPU & Memory).

I’m not sure if its because of the object or parameters I’m passing to the method. This is what the code looks like

public PartialViewResult ConfigureDebit(RecurrentDebitBindingModel model)
        {
            try
            {
                Logger.Info("About to configure debit with the following parameters");
                Logger.Object("Configuration object", model);
                var invoice = work.GetRepository<Invoice>().Get(x => x.InvoiceNumber == model.InvoiceNumber);
                Logger.Info($"Configuring debit for customer with invoice {invoice.InvoiceNumber}");

                BackgroundJob.Schedule(
                            () => new Core.Tasks.Jobs().ConfigureDebit(invoice, model),
                            model.FirstDebitDate);
                Logger.Info("Debit configuration successful");
                return this.Invoices();
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
                return this.Invoices();
                
            }
        }

It freezes at BackgroundJob.Schedule


#2

I found the problem to be the serialization of the parameters I was passing to the ConfigureDebit method. The invoice parameter is a fairly large object with relationships to other entities in my application, its was taking too much time to serialize hence the spike in CPU and Memory usage.

I fixed this by modifying to method to accept only the fields I needed and not the entire object. See new method signature below:
ConfigureDebit(string customerId, long propertyId, string propertyReference, decimal amount, Enumerations.DebitFrequency frequency, DateTime debitDate )