Skip to main content

07 - Learning Analytics: Data Pipelines with xAPI & Kafka

From the xAPI statement to the Kafka topic and the list of at-risk students: partition key, idempotent consumers, an explainable score and privacy.

What do you think about this article?

At a Glance

From the xAPI statement to the Kafka topic and the list of at-risk students: partition key, idempotent consumers, an explainable score and privacy.

From the student's click to the list of who is about to drop out

A learning analytics pipeline takes four steps in a row: the client describes the event with an xAPI statement, publishes it on a Kafka topic using the student as the key, a consumer processes it idempotently, and the resulting metrics feed a list of at-risk students for the teacher. Three choices decide whether it works, and you see them in the listings: the statement must not contain null values, because the store would reject it; the partition key must be the student, because Kafka guarantees order only inside a partition; and the consumer must tolerate duplicates, because committing after processing cannot guarantee anything else.

Think of a teacher who on Monday wants to know which of their 120 students have not logged in for ten days. Without a common format, every feature of the platform (video, quizzes, forum) tells things in its own way and you need an adapter for each. With xAPI you have a single vocabulary, with Kafka a single place where events arrive in order, and the risk rules become a computation on data that is already clean. The listings are standalone Python modules, run with Python 3.14: the outputs are the real ones. There is no Kafka broker on this machine, so the network part is a schema to adapt and I tell you which one; the rest of the logic really runs. The game events that feed this pipeline are produced by the engine described in Gamification Engine: Architecture and State Machine.

The xAPI statement: who, what, on what

xAPI describes a learning experience as a sentence: an actor (actor) performs an action (verb) on an activity (object), optionally with a result, a context and a timestamp. SCORM tracked little more than "completed" inside an LMS; xAPI lets you tell what happens outside as well, provided the verbs and activities are identified by stable IRIs. The verb "completed" is http://adlnet.gov/expapi/verbs/completed, not the English word, which lives only in display for whoever reads.

statement.py: a statement with no empty values
import json
import uuid
from datetime import datetime, timezone

HOME = "https://platform.example"            # IRI of the system that issues the accounts
ADL = "http://adlnet.gov/expapi/verbs/"
VERBS = {
    "completed": {"id": ADL + "completed", "display": {"en-US": "completed"}},
    "passed": {"id": ADL + "passed", "display": {"en-US": "passed"}},
    "failed": {"id": ADL + "failed", "display": {"en-US": "failed"}},
}


def statement(student_ref, verb, activity, title, when, result=None, course=None):
    """xAPI statement as a dictionary: keys with no value are NOT written."""
    stmt = {
        # same student + same activity + same instant = same id: a retry does not create a duplicate
        "id": str(uuid.uuid5(uuid.NAMESPACE_URL, f"{student_ref}|{activity}|{when.isoformat()}")),
        "actor": {"objectType": "Agent",
                  "account": {"homePage": HOME, "name": student_ref}},   # opaque name, no e-mail
        "verb": VERBS[verb],
        "object": {"objectType": "Activity", "id": f"{HOME}/activities/{activity}",
                   "definition": {"name": {"en-US": title}}},
        "timestamp": when.isoformat(),
    }
    if result:
        stmt["result"] = result
    if course:
        stmt["context"] = {"contextActivities": {"parent": [{"id": f"{HOME}/activities/course/{course}"}]}}
    return stmt


def find_nulls(node, path="$"):
    """xAPI: the LRS MUST reject null values outside extensions."""
    if node is None:
        return [path]
    if isinstance(node, dict):
        return [p for k, v in node.items() for p in find_nulls(v, f"{path}.{k}")]
    if isinstance(node, list):
        return [p for i, v in enumerate(node) for p in find_nulls(v, f"{path}[{i}]")]
    return []


if __name__ == "__main__":
    when = datetime(2026, 3, 10, 9, 15, tzinfo=timezone.utc)
    s = statement("u-7f3a", "completed", "lesson/fractions-2", "Equivalent fractions", when,
                  result={"completion": True, "duration": "PT540S", "score": {"scaled": 0.85}},
                  course="matematica-1")
    for chiave in ("id", "actor", "verb", "result"):
        print(chiave, json.dumps(s[chiave], ensure_ascii=False, sort_keys=True))
    print("nulls found:", find_nulls(s))
    ingenuo = dict(s, result={"score": None, "success": None, "completion": True})
    print("with empty fields:", find_nulls(ingenuo))
    print("retry same id:", s["id"] == statement("u-7f3a", "completed", "lesson/fractions-2", "x", when)["id"])

# Output (executed):
# id "5c32d2db-387a-56bc-b634-0dbcbc8c0454"
# actor {"account": {"homePage": "https://platform.example", "name": "u-7f3a"}, "objectType": "Agent"}
# verb {"display": {"en-US": "completed"}, "id": "http://adlnet.gov/expapi/verbs/completed"}
# result {"completion": true, "duration": "PT540S", "score": {"scaled": 0.85}}
# nulls found: []
# with empty fields: ['$.result.score', '$.result.success']
# retry same id: True

The listing makes two choices that the most widespread versions of this example get wrong. First: the actor is an account with an opaque name (u-7f3a), not an mbox with the student's e-mail. The xAPI specification recommends an opaque account name when there is a fear of revealing personal data, and in analytics you do not need to know who it is, you need to recognise them. Second: the statement is a dictionary built only with the keys that have a value. The specification says that the store, the Learning Record Store (LRS), must reject statements with null values outside extensions. If you build it with a dataclass and serialise it with asdict, every unused optional field becomes null and the LRS answers with an error: the output shows find_nulls finding $.result.score and $.result.success in the "naive" statement and nothing in the correct one.

What remains is the id: it is a UUID derived (uuid5) from student, activity and instant, so if the client repeats the send after a timeout the statement has the same id, as the last line shows (True). This is what lets you recognise duplicates further down. If your client can generate two different events at the same instant on the same activity, add a counter to the string from which the id is derived.

Kafka: order per student and unavoidable duplicates

A Kafka topic is divided into partitions, and according to the documentation each partition is a totally ordered sequence, read by a single consumer per group at a time. Order between different partitions does not exist. That is why the message key is the student: Kafka uses it to choose the partition, so all the events of a student end up in the same one and you find them in the order in which they arrived. The documentation gives the same example, with the user id as key. If you used the course as the key you would have order per course, and the partitions of heavily attended courses would become unbalanced.

producer and consumer with aiokafka (schema to adapt)
# Schema to adapt: requires a Kafka broker and the aiokafka package, both absent here. NOT executed.
from aiokafka import AIOKafkaConsumer, AIOKafkaProducer
import json

producer = AIOKafkaProducer(
    bootstrap_servers="kafka:9092",
    acks="all",                  # the broker confirms after the write to all in-sync replicas
    enable_idempotence=True,     # a retry does not duplicate in the log (it is not "exactly-once" by itself)
    linger_ms=10,                # waits up to 10 ms to fill the batch (default 0)
    key_serializer=lambda k: k.encode(),
    value_serializer=lambda v: json.dumps(v).encode(),
)
# send: same account.name -> same key -> same partition -> order preserved
# await producer.send_and_wait("xapi.statements", key=student_ref, value=statement)

consumer = AIOKafkaConsumer(
    "xapi.statements",
    bootstrap_servers="kafka:9092",
    group_id="analytics-aggregator",
    enable_auto_commit=False,    # you decide the commit, after processing (default: True)
    auto_offset_reset="earliest",  # a new group starts from the beginning of the topic (default: "latest")
    value_deserializer=lambda v: json.loads(v.decode()),
)
# async for msg in consumer:
#     await handle(msg.value)      # handle must be idempotent
#     await consumer.commit()

Every property here is a compromise. acks="all" waits for the replicas' confirmation: slower than a single confirmation, but an accepted event is not lost when a node fails. enable_idempotence=True is often described as "exactly-once"; according to the Kafka documentation it guarantees only that a resend does not create duplicates in the log, by assigning each producer an identifier and a sequence. The aiokafka default is False. Transactional delivery (transactional_id, also absent by default) is another thing and serves to write atomically across several partitions: a circulating example uses it in send_batch without having configured it. On the consumer, enable_auto_commit=False puts the commit in your hands, whereas the default is automatic every five seconds even if processing is not finished, and auto_offset_reset is "latest": with the default value a new group ignores the history. I could not run this block: the default values are those reported by the aiokafka documentation (version 0.15).

consumer_sim.py: at-least-once with a crash before the commit
"""Simulated at-least-once consumer: commit AFTER processing, one crash midway."""

LOG = [{"id": f"st-{i}", "student": "u-1", "verb": "completed"} for i in range(1, 6)]


def run(log, handler, broker, crash_at=None):
    """Restarts from the last offset saved in the broker; the commit happens once the message is done."""
    for offset in range(broker["committed"], len(log)):
        handler(log[offset])
        if crash_at == offset:
            raise RuntimeError(f"crash after processing offset {offset}, BEFORE the commit")
        broker["committed"] = offset + 1


def make_handler(idempotent):
    seen, counter = set(), {"completed": 0}

    def handle(stmt):
        if idempotent:
            if stmt["id"] in seen:
                return
            seen.add(stmt["id"])
        counter["completed"] += 1
    return handle, counter


for idem in (False, True):
    handler, counter = make_handler(idem)
    broker = {"committed": 0}
    try:
        run(LOG, handler, broker, crash_at=2)
    except RuntimeError as e:
        print("  ", e)
    run(LOG, handler, broker)                        # restart: resumes from the last commit
    print(f"idempotent handler={idem}: lessons counted = {counter['completed']} (real events: {len(LOG)})")

# Output (executed):
#    crash after processing offset 2, BEFORE the commit
# idempotent handler=False: lessons counted = 6 (real events: 5)
#    crash after processing offset 2, BEFORE the commit
# idempotent handler=True: lessons counted = 5 (real events: 5)

The listing simulates without Kafka what happens when the commit follows processing. The consumer processes offset 2, stops before saving the position, and on restart begins again from the last commit: offset 2 is processed twice. The difference is all in the line with seen. Without the check the output counts 6 lessons out of 5 real events; with the check on the statement id it counts 5. The Kafka documentation says to read "exactly-once" claims carefully, and this is the reason: if you want the result to be correct, the handler must be able to receive the same message twice. It is the same principle as the badges in the article on the gamification engine, here applied to the statement id instead of a database constraint.

The opposite choice (commit before processing) gives "at most once" semantics: no duplicates, but a crash loses the message. For analytics, where a lost event skews the metrics and a double event is discarded with the id, the first is almost always preferable. A caveat on the listing: the seen dictionary lives in memory and is reset on restart; in production the set of ids already seen sits in a store (a table with a uniqueness constraint, as for badges) or has an expiry.

Dropout risk: a rule-based score, honest about its limits

The completion rate is the most useful indicator for whoever runs a course, and the moment to intervene is before the student quits. A rule-based model predicts nothing: it adds up five weighted signals, and has the merit that you can explain to a teacher why a student is on the list. A model trained on history can do better, but you need a known outcome (who really dropped out) over a number of courses that a new platform does not have. Start from the rules, record the outcome, and move to a model only when you have the data to measure whether it beats them.

dropout.py: five signals, declared weights
from dataclasses import dataclass

WEIGHTS = {"inactivity": 0.35, "progress": 0.25, "quiz": 0.20, "sessions": 0.15, "frustration": 0.05}
LEVELS = [(0.3, "low"), (0.6, "medium"), (0.8, "high")]      # above 0.8: critical


@dataclass(frozen=True)
class Metrics:
    days_inactive: int
    completion: float          # 0..1
    avg_quiz: float            # 0..100
    quiz_failure_rate: float   # 0..1
    sessions_30d: int
    rewatch_rate: float
    help_requests_7d: int


def inactivity(days):
    for limit, value in ((1, 0.0), (3, 0.2), (7, 0.5), (14, 0.8)):
        if days <= limit:
            return value
    return 1.0


def risk(m):
    parts = {
        "inactivity": inactivity(m.days_inactive),
        "progress": 1.0 - m.completion,
        "quiz": (max(0, (60 - m.avg_quiz) / 60) + min(m.quiz_failure_rate * 1.5, 1.0)) / 2,
        "sessions": 1.0 - min(m.sessions_30d / 10, 1.0),
        "frustration": min(m.rewatch_rate + m.help_requests_7d * 0.1, 1.0),
    }
    score = sum(parts[k] * WEIGHTS[k] for k in WEIGHTS)
    level = next((name for limit, name in LEVELS if score < limit), "critical")
    top = max(parts, key=lambda k: parts[k] * WEIGHTS[k])
    return round(score, 3), level, top


if __name__ == "__main__":
    print("sum of weights:", round(sum(WEIGHTS.values()), 2))
    casi = {
        "steady": Metrics(0, 0.6, 78, 0.1, 12, 0.3, 0),
        "slowing": Metrics(5, 0.35, 61, 0.3, 4, 0.8, 1),
        "vanished": Metrics(16, 0.2, 48, 0.6, 1, 0.5, 0),
    }
    for nome, m in casi.items():
        print(nome, risk(m))

# Output (executed):
# sum of weights: 1.0
# steady (0.13, 'low', 'progress')
# slowing (0.517, 'medium', 'inactivity')
# vanished (0.82, 'critical', 'inactivity')

The weights (35% inactivity, 25% progress, 20% quizzes, 15% sessions, 5% frustration) are in the WEIGHTS dictionary and the first line of the output confirms they sum to 1. They are my choices, not measurements: no source tells you that inactivity is worth 35%, and the first serious job on your dataset is to calibrate them. The level thresholds (0.3, 0.6, 0.8) are just as arbitrary. The "steady" student (active today, 60% of the course, quiz at 78) gets 0.13: low. "Slowing" (idle for 5 days, quiz at 61, 4 sessions in 30 days) gets 0.517: medium. "Vanished" (idle for 16 days) gets 0.82: critical.

The last element of the tuple, top, is the factor that weighs most on the score: it is what makes the list useful, because "critical for inactivity" and "critical because the quizzes are going badly" call for different interventions (a message versus a catch-up session). A limit to declare to teachers: the score does not distinguish who stopped because the course is too easy from who stopped because it is too hard, and a student can be "critical" because they finished early. Never use a score like this for decisions about the student (grades, exclusions): it is a signal to start a conversation.

Hourly aggregations: Faust is not Kafka Streams

For per-course and per-hour metrics you need to process the stream as it passes. Kafka Streams is a client library for Java and Scala, which runs inside your applications (not "inside the cluster"); Faust, usually cited for Python, is a library that, according to its documentation, brings the ideas of Kafka Streams to Python. They are two different things: choosing Faust means adopting a library with a lifecycle of its own, to be evaluated like any dependency. The code that follows isolates the part that matters, namely the aggregation function, which is tested without either of them.

aggregate.py: the aggregation function, pure
import json


def hour_key(course, timestamp):
    return f"{course}:{timestamp[:13]}"              # '2026-03-10T09:15:00+00:00' -> '...T09'


def course_of(statement):
    for act in statement.get("context", {}).get("contextActivities", {}).get("parent", []):
        if "/activities/course/" in act["id"]:
            return act["id"].split("/activities/course/")[-1]
    return None


def fold(table, statement):
    """Updates the hourly metrics table. JSON-only values: no sets."""
    course = course_of(statement)
    if course is None:
        return table
    key = hour_key(course, statement["timestamp"])
    row = dict(table.get(key, {"events": 0, "students": [], "completed": 0, "passed": 0, "failed": 0}))
    row["events"] += 1
    student = statement["actor"]["account"]["name"]
    if student not in row["students"]:
        row["students"] = row["students"] + [student]
    verb = statement["verb"]["id"].rsplit("/", 1)[-1]
    if verb in ("completed", "passed", "failed"):
        row[verb] += 1
    return {**table, key: row}


def mk(student, verb, ts):
    return {"actor": {"account": {"name": student}}, "timestamp": ts,
            "verb": {"id": "http://adlnet.gov/expapi/verbs/" + verb},
            "context": {"contextActivities": {"parent": [{"id": "https://p.example/activities/course/mat-1"}]}}}


if __name__ == "__main__":
    flusso = [mk("a", "completed", "2026-03-10T09:05:00+00:00"), mk("b", "passed", "2026-03-10T09:20:00+00:00"),
              mk("a", "failed", "2026-03-10T09:40:00+00:00"), mk("a", "completed", "2026-03-10T10:01:00+00:00")]
    tabella = {}
    for st in flusso:
        tabella = fold(tabella, st)
    for k, v in sorted(tabella.items()):
        print(k, json.dumps(v))
    print("without course:", fold({}, {"timestamp": "x", "context": {}}))

# Output (executed):
# mat-1:2026-03-10T09 {"events": 3, "students": ["a", "b"], "completed": 1, "passed": 1, "failed": 1}
# mat-1:2026-03-10T10 {"events": 1, "students": ["a"], "completed": 1, "passed": 0, "failed": 0}
# without course: {}

fold receives the current table and a statement and returns a new table: it never modifies the input, so the same function serves in a Faust agent, in a batch job or in a test. The key is "course:hour", obtained by truncating the ISO timestamp to the first 13 characters. In the output, four statements become two rows: three events at 09, one at 10, with two distinct students in the first. The distinct students are a list and not a set: a persistent table serialises its values, typically as JSON, and a set is not serialisable. Checking student not in row["students"] is linear, acceptable for a few thousand students per hour and course; beyond that, you need an approximate structure such as HyperLogLog.

One choice to be aware of: the function counts only the statements with the three verbs we care about and ignores the others, but it does not compute the quiz average. An average computed only on the quizzes passed, as you find in several examples, is inflated, because failed attempts do not enter the average. For a correct average the score must be carried in the failed statements too. If a statement has no course in its context, the function returns the table unchanged, as the last line shows.

The teacher's dashboard: the query that answers the question

The dashboard answers a few questions: who is idle, for how long, with what risk. The original example in this article joined five tables with as many LEFT JOINs in a single query: if one of the tables has more rows per student and course, the rows multiply and every AVG or COUNT above that join is wrong without any error signalling it. The version below does a single join between two tables with one row per student and course, and is run on SQLite with test data.

atrisk.py: list of students per course, with an optional filter
import sqlite3

conn = sqlite3.connect(":memory:")
conn.executescript("""
CREATE TABLE dropout_risk (student_id TEXT, course_id TEXT, risk_level TEXT, risk_score REAL);
CREATE TABLE student_activity (student_id TEXT, course_id TEXT, last_activity TEXT);
INSERT INTO dropout_risk VALUES ('s1','mat-1','critical',0.91), ('s2','mat-1','high',0.72),
                                ('s3','mat-1','low',0.12), ('s4','fis-1','high',0.65);
INSERT INTO student_activity VALUES ('s1','mat-1','2026-02-20'), ('s2','mat-1','2026-03-04'),
                                    ('s3','mat-1','2026-03-09'), ('s4','fis-1','2026-03-01');
""")

QUERY = """
SELECT r.student_id, r.risk_level, r.risk_score,
       CAST(julianday('2026-03-10') - julianday(a.last_activity) AS INTEGER) AS days_idle
FROM dropout_risk r
JOIN student_activity a ON a.student_id = r.student_id AND a.course_id = r.course_id
WHERE r.course_id = :cid
  AND (:risk IS NULL OR r.risk_level = :risk)
ORDER BY r.risk_score DESC
LIMIT 100
"""
print("all levels:", conn.execute(QUERY, {"cid": "mat-1", "risk": None}).fetchall())
print("critical only :", conn.execute(QUERY, {"cid": "mat-1", "risk": "critical"}).fetchall())
print("other course  :", conn.execute(QUERY, {"cid": "fis-1", "risk": None}).fetchall())

# Output (executed):
# all levels: [('s1', 'critical', 0.91, 18), ('s2', 'high', 0.72, 6), ('s3', 'low', 0.12, 1)]
# critical only : [('s1', 'critical', 0.91, 18)]
# other course  : [('s4', 'high', 0.65, 9)]

The optional filter is (:risk IS NULL OR r.risk_level = :risk): with None it returns all the levels (first line of the output), with "critical" only the critical ones (second), and :cid separates the courses (third line: the physics student does not appear in maths). The idle days are computed by julianday, specific to SQLite; in PostgreSQL you use CURRENT_DATE - last_activity. On PostgreSQL the :risk parameter used only in IS NULL may require an explicit cast (CAST(:risk AS text)) because the driver cannot infer its type: I could not try it here. LIMIT 100 avoids an enormous response for a large course; for a complete list you need pagination.

Privacy: what you must decide before collecting

Learning data is personal data, and with underage students the care must be greater. There is no universal checklist, but the GDPR gives three fixed points that affect the design, and it is worth turning them into decisions made before writing code.

  • Minimisation (art. 5): collect only the data adequate and relevant to the purpose; that is why the actor is an opaque name and the text of the answers does not enter the statements.
  • Storage limitation (art. 5): set how long you keep the raw events and delete them at expiry; the hourly aggregates are enough for most questions.
  • Erasure (art. 17): if a data subject requests it and the conditions apply, you must be able to delete their data, so you need a way to find all the events of an account.
  • Legal basis (art. 6): consent is one of the possible bases, not the only one; the choice depends on the context and must be made with whoever handles privacy for your customer.
  • Minors (art. 8): for services offered directly to minors and based on consent, under 16 you need the authorisation of whoever holds parental responsibility, and Member States may lower the age down to 13.

The criterion that holds the list together is that privacy is designed on the data side, not the interface side. An opaque name makes deletion and pseudonymisation much easier than an e-mail scattered across ten tables; an expiry decided at the start costs one line of configuration, decided after a complaint it costs a migration. The point that requires a professional is the last one: the age of consent for minors varies from State to State and the legal basis for a school is often different from consent. This article is not legal advice.

Frequently asked questions

Does xAPI replace SCORM?

In new projects yes, almost always: xAPI tracks activities even outside an LMS and with an extended vocabulary. SCORM remains in use where the content is already packaged in that format; the two are often used together.

Do I need Kafka to do learning analytics?

No, for small volumes it is enough to write the statements to a database and query them. Kafka becomes useful when events arrive in large quantities, you need to reprocess the history with new rules, and several consumers read the same stream.

Why is the partition key the student?

Because Kafka guarantees order only inside a partition and uses the key to choose it. With the student as the key, the events of one person arrive in the order in which they were produced.

Can a risk score decide who fails?

No. It is a signal to start a conversation or offer support, computed with arbitrary weights and thresholds. Using it for decisions about the student would require validation on real data and, in the European Union, checking the rules on automated processing.

What you can do now

You can build an xAPI statement that an LRS accepts, choose the partition key that preserves order per student, write a consumer that survives a restart without counting twice, compute an explainable risk score and query the list of at-risk students without multiplying rows. The next problem is getting several people to work together on the same material: you find it in Real-Time Collaboration in EdTech. If instead you need the architecture of the platform where these events originate, start from Scalable LMS Architecture.

Sources

All listings except the producer and consumer schema were run with Python 3.14; the SQL query runs on SQLite, not on PostgreSQL. The real behaviour with a Kafka broker was not tried. The weights and thresholds of the score are design choices, not measurements.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects