pavancse17
Handling failed Oban jobs
Hey Devs,
I have been using Oban — Oban v2.5.0 (hexdocs.pm) in one of my phoenix application. My requirement is like when job fails after trying couple of times based on the max attempts that has been configured to that job. I need to update that job has been failed in DB and give an option to retry the job. I am able to accomplish this using Oban.Telemetry — Oban v2.5.0 (hexdocs.pm) events & Oban.retry. But is there a better way like a call back that can be written within the worker that will be called when job fails?
Marked As Solved
sorentwo
Nope. That is exactly how you’d handle that!
Now, I’m not sure why you’re double-tracking records in the DB, but that’s entirely your prerogative ![]()
Also Liked
sorentwo
If you mean that you want to automatically retry it based on some criteria, then telemetry + retry is the exact mechanism you need. The telemetry events run within the job’s process and are provided in lieu of various hooks.
If this is something you want to do periodically, you can use a cron job that retries for you. Or, if it is something that is more manual based on some inspection, you can retry using the database queries (or the web dashboard).
pavancse17
I guess my question is not clearly framed. My requirement is like below:
- I have a table called
job_a_trackerwith fields likeid, failed_job_id, statusand the job calledheavy_job. - Before i trigger the
heavy_jobI will create a record injob_a_trackerwithstatus="started"& then trigger it. - Now when job completes successfully I can very well update the status in
job_a_trackerby keeping it as a last statement in the worker. - But tricky part is when job gets failed. I need to save the failed_job_id and update status as Failed.
Right now I attached something like this in application.ex file:
:telemetry.attach(
"oban-logger",
[:oban, :job, :exception],
&MyApp.JobTracker.handle_event/4,
nil
)
defmodule MyApp.JobTracker do
require Logger
def handle_event(
[:oban, :job, :exception],
%{duration: duration},
%{
attempt: attempt,
max_attempts: max_attempts,
worker: "MyApp.HeavyJob"
} = meta,
nil
) do
# update record with failed_job_id = meta.id & status = "Failed"
end
end
Is there a better way to handle this ?
sorentwo
Absolutely. The job is stored in the database within the oban_jobs table and has a state field on it. You can link to them or even set up foreign keys to track the job. The telemetry events will also let you immediately notify a user that the job succeeded or failed.







