When a Rails job receives an Active Record object through perform_later, how does GlobalID carry it, and when is ActiveJob::DeserializationError raised?
answer
- a URI, not the attributes
- gid://app/Model/id
- GlobalID::Locator.locate calls find
- row gone: RecordNotFound wrapped
- unsaved record: SerializationError at enqueue
basics
~20 sActive Job stores an Active Record argument as a GlobalID string such as gid://academy/Enrollment/42 and reloads it with find when the job runs; if that lookup fails, typically because the row was deleted, ActiveJob::DeserializationError is raised before perform starts.
solid answer
~40 sActive Record includes `GlobalID::Identification`, so Active Job serializes a record as `{"_aj_globalid" => "gid://academy/Enrollment/42"}` instead of copying its attributes. When the worker runs the job, `GlobalID::Locator.locate` parses the URI and calls `Enrollment.find(42)`, so `perform` sees the row as it is *now*, not as it was at enqueue time. Any exception while rebuilding the arguments, most often `ActiveRecord::RecordNotFound` because the row was deleted in between, is wrapped in `ActiveJob::DeserializationError`, with the original as its `cause`. It is raised inside `perform_now` before `perform` runs, so a `rescue_from` handler can take it; the generated `ApplicationJob` carries a commented-out `discard_on ActiveJob::DeserializationError`. An unsaved record has no id, so `perform_later` raises `ActiveJob::SerializationError` in the caller instead.
go deeper
Remember that you pass the record itself and Active Job turns it into a GlobalID reference that the worker loads again.
Walk through serialize and locate: the gid URI, find on the worker, and which failures become DeserializationError versus SerializationError.
Diagnose a burst of DeserializationError: deleted rows are routine, but jobs racing uncommitted transactions are a bug that discarding would hide.
Weigh passing references against passing values across a whole job catalogue, given deletes, renames during deploys and enqueue-time snapshots.
## Why jobs do not carry the record itself A queued job has to survive being written to a database table or a Redis list and read back by another process, possibly on another machine, minutes later. So Active Job stores only JSON-safe data. Copying a record's attributes into the payload would be bulky and would hand the job a stale snapshot. Instead, Active Job passes a **reference** the worker can resolve: a **GlobalID**. **GlobalID** is a small library (version 1.4 at this pin) that gives an object an application-wide URI. Any class that includes `GlobalID::Identification` gets `to_global_id` (alias `to_gid`); Active Record includes it in every model. For an enrollment in an app named `academy` the URI looks like `gid://academy/Enrollment/42`: the app name, the model class name and the primary key. The app name defaults to the Rails application's name and can be set through `config.global_id.app`. ## The round trip 1. `GenerateCertificateJob.perform_later(enrollment)` reaches serialization. `ActiveJob::Arguments` sees a `GlobalID::Identification` and writes `{"_aj_globalid" => "gid://academy/Enrollment/42"}`. 2. If the record has no id yet, building the GlobalID fails and Active Job raises **`ActiveJob::SerializationError`** in the caller: nothing is queued. 3. On the worker, the job is rebuilt from the payload. Its arguments are deserialized lazily, at the start of `perform_now`. 4. `GlobalID::Locator.locate` parses the URI, constantizes the model name and calls `Enrollment.find(42)`. 5. If anything in that step raises, `Arguments.deserialize` rescues it and raises **`ActiveJob::DeserializationError`**, whose message starts with "Error while trying to deserialize arguments" and whose `cause` is the original exception. ```ruby class GenerateCertificateJob < ApplicationJob discard_on ActiveJob::DeserializationError def perform(enrollment) CertificatePdf.new(enrollment).attach! end end ``` ## What the payload looks like Serializing the job produces a plain hash that the adapter stores. For the certificate job it contains, among other keys: ```json { "job_class": "GenerateCertificateJob", "queue_name": "certificates", "arguments": [{ "_aj_globalid": "gid://academy/Enrollment/42" }], "executions": 0, "locale": "en", "timezone": "UTC" } ``` Only the reference travels, which keeps payloads small no matter how wide the `enrollments` table is. The caller's `locale` and `timezone` travel too, and the worker runs `perform` inside them, so the certificate is rendered in the learner's language even though the worker has no request. ## When `DeserializationError` happens | Situation | Underlying error | Wrapped as | |---|---|---| | The enrollment was destroyed after enqueueing | `ActiveRecord::RecordNotFound` from `find` | `DeserializationError` | | The model class was renamed or removed in a deploy | `NameError` from constantizing | `DeserializationError` | | A custom serializer named in the payload no longer exists | `ArgumentError` | `DeserializationError` | | The record was never saved | building the GlobalID fails | `SerializationError`, at enqueue | The common production cause is the first row: a learner deletes their account, or an admin removes a course, while certificate jobs for it are still queued. A related one is a job enqueued **inside a transaction that has not committed yet**: the worker's connection cannot see the new row and `find` fails the same way. ## Handling it - Because the error is raised inside `perform_now`, it goes through the job's `rescue_from` handlers like any other exception. The generated `ApplicationJob` ships the line `discard_on ActiveJob::DeserializationError` commented out, with the note that most jobs are safe to drop when their records are gone. Whether and how to discard or retry is the retry rules' subject; here the point is knowing what the error means. - Discarding blindly can hide a real bug, such as a job racing an uncommitted transaction. If the record should have existed, the cure is to enqueue after commit, not to swallow the error. ## Choosing what to pass - **Pass the record** when the job should act on the current state: the certificate must show the learner's name as it is when the PDF renders. - **Pass plain values** (ids, strings, numbers) when the job must use the state *at enqueue time*, such as the score the learner had at completion, or when the record may legitimately be gone and the job should carry on. - **Never pass a whole attributes hash** to dodge GlobalID: it bloats every payload and silently freezes data that may change before the job runs. - GlobalID in a job payload is **unsigned**. The signed variant, `to_sgid`, with a one-month default expiry, exists for references that travel through untrusted places such as URLs or form fields; a server-side queue does not need it.
- Does perform see the record as it was at enqueue time?No. The payload holds only the GlobalID URI, so the worker runs `find` and gets the row's current state. A learner who corrected their name between enqueue and perform gets the corrected name on the certificate. If the job must use enqueue-time values, pass those values as plain arguments.
- Why can an enqueue inside a transaction produce DeserializationError even though the record exists?The worker uses its own database connection, which cannot see rows the caller's transaction has not committed. If the job is pushed before the commit and a worker picks it up quickly, `Enrollment.find` raises `ActiveRecord::RecordNotFound`, which Active Job wraps. Deferring the enqueue to commit removes the race; discarding the error would only hide it.
A GlobalID is a library call number rather than a photocopy of the book: the worker goes to the shelf when it needs the book, gets the current edition, and finds an empty slot if the book was withdrawn in the meantime.
- Active Job stores the record's attributes in the payload and rebuilds it from them
- If the record was deleted, perform simply receives nil
- DeserializationError is raised at perform_later time in the caller
- An unsaved record is saved automatically so it can be enqueued
- Job payloads use signed GlobalIDs that expire after a month