diff --git a/docs/decisions/0002-transactional-outbox-for-data-sinks.rst b/docs/decisions/0002-transactional-outbox-for-data-sinks.rst new file mode 100644 index 00000000..e0606483 --- /dev/null +++ b/docs/decisions/0002-transactional-outbox-for-data-sinks.rst @@ -0,0 +1,342 @@ +0002 Transactional Outbox for the Data Sinks +############################################ + +Status +****** + +**Proposed** + +Context +******* + +Aspects keeps its own copy of platform information in ClickHouse so that it can be shown in reports: courses and +their blocks, custom courses (CCX), enrollments, learner profiles, external identifiers, tags, object tags, +taxonomies, pathways, pathway enrollments and competencies. Each kind of information has a data sink in this +repository. + +Today every change to one of those records makes a signal receiver queue a separate Celery task that serializes +that single record and inserts it into ClickHouse: + +* **No batching.** A thousand enrollments mean a thousand tasks and a thousand HTTP inserts, and ClickHouse advises + against many small inserts. +* **Shared workers.** The tasks run on the platform's Celery workers and wait up to five seconds for ClickHouse, so + a slow analytics database delays unrelated platform work. Operators run more workers to keep up, which raises + costs. Every course publish, and every tag added to or removed from a course, sends the whole course again, which + is the heaviest task in large courses. Some changes queue a second task. +* **Work for turned-off sinks.** Most receivers queue the task even when the data sink is turned off; the task + only checks it when it runs. +* **Lost changes.** By default Celery does not retry a failed task, and a task that a worker stops in the middle of + is not run again. A change whose send fails never reaches ClickHouse, and reports stay incomplete until someone + runs a full manual reload (``dump_data_to_clickhouse``). + +Most receivers already wait for the commit (``transaction.on_commit``) before queuing the task, so a rolled-back +change is never sent; the course publish, user retirement and object tag deletion receivers queue it directly. +Nothing, however, records a committed change whose task was lost. + +The sources describe this problem as a "dual write": the platform writes the change to MySQL and separately sends it +to another system, and no single transaction covers both writes. The `transactional outbox`_ pattern solves it by +storing the message in the same transaction as the business data and sending it from a separate process. + +A proof of concept of this decision was built for the course enrollment data sink. It confirmed that the outbox row +is committed or rolled back with the enrollment change, that no Celery task is queued, that many changes become a +few inserts with the same rows as today, and that no change is lost when ClickHouse fails. + +Decision +******** + +The data sinks will stop queuing one Celery task per change. Instead, every signal receiver will write a small row +into an outbox table in MySQL, in the same transaction as the platform change, and a management command will send +the outbox to ClickHouse in batches. + +Outbox table +============ + +The plugin adds one generic ``SinkOutbox`` model, shared by every data sink, with these columns: + +* ``id``: auto-increment primary key. It defines the order in which rows are read. +* ``sink``: model name of the data sink that must process the row (for example ``course_enrollment``). +* ``object_id``: primary key of the record, stored as text so that it covers integers, UUIDs and course keys. +* ``operation``: ``upsert`` or ``delete``. +* ``created``: when the change was recorded. +* ``attempts``: number of failed send attempts, starting at 0, with no maximum. +* ``last_error``: text of the last error, truncated to 2000 characters. +* ``last_attempt_at``: when the last failed attempt happened. +* ``is_active``: only active rows are read by the command. + +An index on ``(sink, is_active, id)`` lets the command read each sink's active rows in order. + +The table has no unique constraint on ``(sink, object_id)``: several rows for the same record are allowed. A unique +constraint would force an upsert inside the request transaction, which adds lock contention and loses the changes +made while a send is in flight (the in-flight row would be updated and then deleted). + +Receivers +========= + +Every receiver keeps listening to the signal it uses today, and follows the same order of checks: + +#. If the data sink is not enabled (``is_enabled()``), it does nothing: no outbox row and no task. +#. If the sink is enabled and uses the outbox, it writes the outbox row directly, without + ``transaction.on_commit``, so the row is part of the same transaction as the change. A rollback removes both, + and a commit persists both. +#. Otherwise, while the outbox is not yet the default (see "Switching each sink to the outbox"), it queues the + Celery task exactly as today. + +The outbox insert runs inside a savepoint (a nested ``transaction.atomic()``). If it fails, only the savepoint is +rolled back, the error is logged and the user's request continues; that change is not recorded, as happens today +when queuing the Celery task fails. A deadlock is the exception: InnoDB rolls back the whole transaction, so the +request fails. The receivers only insert into the outbox and the command deletes by primary key, so deadlocks there +are expected to be rare. + +Course publishes and user retirements are covered too, because both are backed by MySQL: + +* **Course publish:** the content lives in the modulestore, but the pointer to the published version lives in MySQL + (``SplitModulestoreCourseIndex.published_version``) and is saved before ``COURSE_PUBLISHED`` is sent, on the same + database connection the receiver uses. It is either already committed when the signal arrives (the Studio xblock + handler runs in autocommit) or part of the same transaction as the outbox row (paths under ``ATOMIC_REQUESTS``). + ``COURSE_PUBLISHED`` is sent with ``send_robust``, so any error that escapes the receiver is only logged by the + platform. +* **User retirement:** ``USER_RETIRE_LMS_MISC`` is sent inside the retirement request's ``ATOMIC_REQUESTS`` + transaction, so the outbox row commits with the retirement changes. + +The receivers write these rows: + +.. list-table:: + :header-rows: 1 + + * - Signal + - Outbox rows + * - Course published (``COURSE_PUBLISHED``) + - ``upsert`` of ``course_overviews`` for the course key. + * - Object tag saved or deleted + - A saved object tag writes an ``upsert`` of ``object_tag``. When the tagged object is a course, a saved or + deleted object tag also writes an ``upsert`` of ``course_overviews`` for the course. + * - Enrollment status changed (``ENROLL_STATUS_CHANGE``) + - ``upsert`` of ``course_enrollment``. The signal only carries the user and the course, so the receiver also + looks up the enrollment id. + * - User profile, external id, tag, taxonomy (including competency taxonomies), pathway, pathway enrollment and + learner competency status saved + - ``upsert`` of the record in its data sink. + * - Learner competency course status saved + - ``upsert`` of ``student_competency_course_status``, only for the course-level rows the sink sends, as today. + * - Pathway deleted + - ``delete`` of ``catalog_pathway``. The id is read in the receiver, before Django clears it. + * - User retired (``USER_RETIRE_LMS_MISC``) + - ``delete`` of the user in the user retirement data sink. + +Because a turned-off sink writes nothing, turning off the learner profile and external identifier sinks stops +them from writing outbox rows. + +Switching each sink to the outbox +================================= + +Each data sink gets an ``is_outbox_enabled()`` method next to ``is_enabled()``, controlled by the Django setting +``EVENT_SINK_CLICKHOUSE__OUTBOX``. The setting is read with a default, so it only needs to be defined for the +sinks that use the outbox. It is off by default at first, so installing the new version changes nothing until an +operator opts in, and each sink can be moved to the outbox and compared with the Celery path on its own. + +A waffle flag may be added on top of the setting, with the flag (when it exists) taking precedence. The edx-toggles +``WaffleFlag`` API cannot tell a missing flag from a false one and, outside a request, queries the database and logs +a warning on every call, so it would have to read waffle's ``Flag`` model directly. + +Once every sink has been validated through the outbox, the outbox becomes the default and the per-change Celery +path is removed. + +Sending the outbox +================== + +One send function, shared by the management command and the Django admin, processes a set of outbox rows: + +* It reads the rows of each sink in batches, in ``id`` order, and never reads the same row twice in a run, so rows + that stay in the outbox are left for the next run. +* It skips the rows of a sink that is not enabled, or that is unknown, and logs it: those rows are not sent, deleted + or counted, so they are sent if the sink is turned on again. The outbox setting is not checked: it only decides + what the receivers do with new changes. +* It deduplicates the rows of each batch by record, fetches the records through the sink's queryset (matching + ``object_id`` with the sink's ``pk_format``, so course keys and UUIDs work), serializes them in one batch with the + existing serializer and sends one insert per batch through the existing sink insert path. +* The ``time_last_dumped`` of each record is the most recent ``created`` among its outbox rows, passed to the + serializer through its context. The latest change always wins in ClickHouse, and "Last synchronized" information + stays meaningful. Without that context (backfill command, Celery path) the serializer keeps using the current + time. ``dump_id`` is still a new UUID, and the columns and text formats do not change. +* On success it deletes exactly the outbox row ids that were read and confirmed, never a range such as + ``id <= max``, so a row committed late by a concurrent transaction is never deleted without being sent. + +Serialization happens here, outside any user transaction, never in the request. Its queries run in autocommit, and +plain ``SELECT`` queries take no locks in InnoDB. The only write is the ``get_or_create`` of a learner's missing xAPI +identifier (``ExternalId``), a short row lock that the Celery task already takes today. The delete of the sent rows +is a separate statement, by primary key, so it only locks those rows and does not block the receivers, which insert +new rows with new ids. + +The generic send path only sends the current state of ``upsert`` records. ``delete`` rows are sent only by the sinks +below, which define what a deletion means for them; a sink that starts writing ``delete`` rows has to define it too. + +Some sinks keep their own way of sending, behind the same outbox rows: + +* **Courses.** A ``course_overviews`` row sends the course overview and all its published blocks, and then every + CCX of the course, as the Celery task does today. Several publishes or course tag changes in the same batch become + a single send, with the same ``time_last_dumped`` for the overview and its blocks. +* **Pathway deletions.** A deleted pathway cannot be serialized, so a ``delete`` row keeps copying the pathway's + latest row inside ClickHouse with ``is_deleted = 1``, as the tombstone sink does today. +* **User retirement.** A ``delete`` row of the user retirement sink keeps deleting the user's rows from every table + in the personal information list (``EVENT_SINK_CLICKHOUSE_PII_MODELS``), with one query per table for the whole + batch. Retirement rows are processed after the other sinks in each run, so a pending learner profile or external + identifier change cannot send the user's personal information again after it was deleted. Rows that are sent + outside that order (a row that failed before the retirement and is retried later, the ``--sink`` option or the + admin's **Send now**) are covered by a check in the send function: before sending a learner profile or external + identifier row, it checks whether the platform already retired the user, and if so it deletes the row from the + outbox without sending it. + +Failures stay in the outbox, so nothing is lost and operators can see what is stuck and why: + +* **ClickHouse error** (connection, timeout or HTTP error): every row sent in the failed insert gets ``attempts`` +1, + ``last_error`` and ``last_attempt_at``, stays active, and the error is raised again, which stops the run instead + of hammering an unavailable database. +* **Record no longer exists** (``upsert`` rows only): the row gets ``attempts`` +1 and an error that says so, and it + is deactivated, so the command stops retrying it but it can still be inspected. ``delete`` rows are not subject to + this rule. +* **Serialization error:** the batch is serialized again record by record, so that only the failing records keep + their rows, with ``attempts`` +1 and their error, and the rest of the batch is sent. +* Any other error is raised as is, without touching the rows. + +Management command +================== + +A new ``drain_outbox_to_clickhouse`` management command is a thin layer over the send function. It sends the active +rows once and exits; it has no loop mode. Its options are ``--batch_size`` (default 1000) and ``--sink`` (one data +sink; all of them by default). It exits with an error when ClickHouse fails, so the scheduler can report it. + +The command assumes a single running instance. Concurrent instances may send the same rows twice. The admin's +**Send now** can overlap with a running command in the same way; the rows sent twice carry the same state and +``time_last_dumped``, so the reports do not change. + +Running the command periodically is the job of the infrastructure, provided by tutor-contrib-aspects: + +* **Docker Compose (Tutor local and dev):** a service with the openedx image and the LMS settings, with + ``restart: unless-stopped``, enabled by a Tutor setting such as ``ASPECTS_ENABLE_OUTBOX_DRAINER``. The service + repeats the command (``drain_outbox_to_clickhouse; sleep N``, or a cron scheduler such as supercronic), with the + interval in a Tutor setting such as ``ASPECTS_OUTBOX_DRAINER_INTERVAL`` (default 300 seconds, aligned with the + 5-minute ClickHouse and Superset cache). +* **Kubernetes:** a CronJob with ``concurrencyPolicy: Forbid``, so that runs never overlap, with the schedule in a + Tutor setting such as ``ASPECTS_OUTBOX_DRAINER_SCHEDULE`` (every 5 minutes by default). + +Django admin +============ + +The plugin registers a read-only admin for the outbox (no add, change or delete, so no pending change is removed +without being sent), with the outbox columns, filters by sink, active flag and operation, and search by +``object_id``. Its actions are: + +* **Send now:** queues one Celery task with the selected row ids, which runs the same send function on those rows, + inactive ones included, so an administrator can retry a row they believe is fixed (a record that is still missing + deactivates its row again). The admin reports how many rows were queued, and the outcome is visible in the outbox: + sent rows disappear and failed rows show their error. This is one task per admin action, not per change. +* **Activate** and **Deactivate:** set ``is_active`` on the selected rows and keep their attempts and last error. + +Backfill +======== + +The ``dump_data_to_clickhouse`` command keeps loading existing data exactly as today, without going through the +outbox, including the ``--force`` option that sends unchanged courses. + +Consequences +************ + +* The platform no longer runs one Celery task per change: a request only adds one small insert to the outbox, and + the analytics work leaves the platform's shared workers. +* Changes are no longer lost when ClickHouse is down or a process stops in the middle of a send: the outbox row is + committed with the change and stays until ClickHouse confirms it, with no time limit. +* Many changes become a few inserts, which is what ClickHouse recommends. +* A turned-off data sink writes nothing, neither to ClickHouse nor to the outbox. +* The rows reach ClickHouse with the same columns, values and formats as today, because the current serializers are + kept, including the creation of the learner's xAPI identifier. The ClickHouse tables, dbt models and Superset + reports do not change. +* The current deletion of retired users' personal information is kept. +* Every signal receiver changes, and a migration adds the outbox table. A failure of the outbox insert is logged and + does not fail the user's request, but that change is not recorded; a deadlock still fails the request. +* The outbox is a high-churn table, a known weak spot of InnoDB (purge lag and fragmentation). It is a single table + shared by every data sink, so a new sink adds volume but no new table to tune. The command deletes by primary key + in batches, and operators should monitor the table size and the InnoDB history list length. +* The outbox inserts and deletes run on the primary database, like every sink query today. Reading from a replica + would not work as is, because the serializer's ``get_or_create`` of the xAPI identifier has to read and write on + the primary, so it would need per-query routing. +* The total amount of data read from MySQL stays about the same, but bursts such as a batch enrollment are absorbed + by the outbox and read in fixed-size batches by a single process, instead of one parallel task per change. +* A new process runs with the platform image. It loads the whole platform code, like the ``aspects-consumer`` + service, which matters for small installations, and tutor-contrib-aspects has to add its Compose service and its + first Kubernetes CronJob. +* Changes arrive every few minutes instead of a few seconds after they happen. +* A record that changes several times before the command reads it reaches ClickHouse only in its latest state. +* The outbox grows while the command is stopped, and rows that keep failing stay in it. Operators should monitor + its size and its inactive rows. +* Follow-up work, not part of this decision: a maximum number of attempts or a dead-letter table, locking so that + several instances of the command can run at once (for example ``SELECT ... FOR UPDATE SKIP LOCKED``), and the + waffle flag control. +* This decision only changes how the data is delivered to ClickHouse, not what is sent. No deletes are replicated + to ClickHouse besides the ones that exist today: the deletion of retired users' personal information, and the + pathway tombstone, which is a new row with ``is_deleted = 1``. + +Rejected Alternatives +********************* + +**Copy the platform tables with a log-based change data capture (CDC) tool**, such as PeerDB, Altinity Sink +Connector or mysql_ch_replicator, and turn the copies into the current analytics rows with SQL inside ClickHouse. +It would capture every change, including those made without a platform signal, and it has less impact on the LMS +database, since it reads the binlog instead of writing or querying tables in the request path. It was rejected +because of the data it cannot produce: + +* It cannot produce the course content: the course blocks live in the modulestore's Mongo structures, not in MySQL + tables, so the task per course publish would stay. +* It can only copy what is already stored, so it cannot create the learner's xAPI identifier when it is missing. +* The current serializers (tag lineage, taxonomy type, values taken from other tables) would have to be rewritten as + SQL with no guarantee of identical rows. The backfill would have to be rebuilt the same way. +* If the tool or ClickHouse stops for longer than the binlog is kept (3 days in Tutor), the copy needs a full resync. +* It adds a new service to install, monitor and update (PeerDB's official Docker Compose has 11 services), may + require MySQL settings that are not the defaults (PeerDB requires ``binlog_row_metadata=FULL``), and copies + personal information that the retirement deletion would also have to cover. +* Every platform upgrade that changes a copied table has to be applied to the copy. + +**Copy the platform tables with scheduled queries**, with a tool such as Sling or ingestr, or with ClickHouse table +functions and refreshable materialized views. It needs no change log, but it was rejected because it shares the +serializer and course content problems of CDC, and also: + +* The tables have no "last modified" column, so enrollments, users and profiles would have to be read in full on + every run, with a load on MySQL that has not been measured. +* Queries do not see deleted records without a full reload or a comparison of all keys. +* Data arrives once per run, rows that arrive late may be missed, and a scheduler is needed (except with ClickHouse + table functions, which would keep MySQL credentials in ClickHouse). + +**Improve the current Celery tasks** with retries, ``acks_late``, a dedicated queue and worker, ClickHouse +asynchronous inserts, and no task for turned-off sinks. It keeps the current serializers and needs no new +technology, but it was rejected because: + +* It is still one task and one request per change; grouping them would need Celery beat, whose use in Tutor has not + been checked. +* When the retries run out, the change is still lost. +* The dedicated queue needs its own worker in Docker and in Kubernetes. + +The Open edX event bus was also considered, but its documentation does not describe delivery guarantees or what +happens when publishing fails. + +**Save the serialized rows in MySQL and copy them to ClickHouse** with a CDC or scheduled-query tool, serializing +either in the request or in the Celery task. It keeps the current serializers, but it was rejected because: + +* Every MySQL table would have to follow its ClickHouse table through plugin migrations, and be cleaned after the + copy. +* Personal information would be duplicated in MySQL, so the retirement deletion would have to run there too. +* It still needs a CDC or scheduled-query tool, with their problems described above. +* Serializing in the request adds several reads per change, and more for tag imports, competency calculations and + the creation of xAPI identifiers; the course content would stay in one Celery task per publish. +* Serializing in Celery keeps one task per change, and a failed task still loses the change. + +References +********** + +* `Transactional outbox`_ pattern (microservices.io). +* `Debezium`_: dual writes, log-based change data capture and the outbox pattern. +* `openedx-aspects issue #444`_: proposals to replace the data sinks with a CDC tool. +* `Celery task documentation`_: retries and ``acks_late``. + +.. _transactional outbox: https://microservices.io/patterns/data/transactional-outbox.html +.. _Debezium: https://debezium.io/ +.. _openedx-aspects issue #444: https://github.com/openedx/openedx-aspects/issues/444 +.. _Celery task documentation: https://docs.celeryq.dev/en/stable/userguide/tasks.html