Skip to main content

06 - Gamification Engine: Architecture and State Machines

A solid gamification engine: a state machine, idempotent badges with ON CONFLICT, a windowed Redis leaderboard and daily streaks in the student's time zone.

What do you think about this article?

At a Glance

A solid gamification engine: a state machine, idempotent badges with ON CONFLICT, a windowed Redis leaderboard and daily streaks in the student's time zone.

A gamification engine is an architecture problem, not a badge problem

A gamification engine holds up only if four decisions are made early: the student's progression is an explicit state machine, every reward is granted idempotently thanks to a database constraint, the leaderboard shows a window of peers and not the whole population, and streaks of consecutive days are computed in the student's time zone. Everything else, meaning which badges exist and how many points a lesson is worth, is configuration.

Whoever adds gamification to a platform already in production usually starts from the points and discovers the rest later. The student who receives the same badge twice because the message was reprocessed after an error; the one who loses a fifteen-day streak because they studied at 11:30 pm and the server was counting a different day; the leaderboard in which the new signup ranks 8,412th and stops looking at it. These are design defects, and fixing them afterwards costs more than writing them well once.

The listings in this article are five standalone Python modules, one per decision. They were run with Python 3.14: the outputs in the comments are the real ones. Two modules run on a stand-in, and the text says so where it happens: the badge database is in-memory SQLite and the leaderboard uses an in-memory double of only the Redis commands employed. It plugs into the platform described in Scalable LMS Architecture: in a multi-tenant system every Redis key and every table below must be prefixed or filtered by customer. The source of the events is the pipeline in Learning Analytics with xAPI and Kafka, which follows this article.

Extrinsic and intrinsic motivation: what you can expect from points

Points, badges and leaderboards are extrinsic rewards: they come from outside. Intrinsic motivation is doing something because it is interesting or because you feel more capable. The distinction matters for the design because research on self-determination theory, summarised by Ryan and Deci, reports that expected tangible rewards tend to reduce intrinsic motivation, while choice and feedback on your own competence sustain it. This is not a condemnation of points: it is a warning about where to put them.

A concrete example. A badge "you completed 10 lessons" rewards quantity and leads the student to click their way to ten. A badge "you solved a quiz you got wrong on the first attempt after reviewing it" rewards a behaviour the student recognises as competence. The first is easy to program, the second is better; the engine underneath must allow both, and that is why the rules are data. Whether a mechanic works on a specific course you decide by measuring, not by reading an article.

The state machine: where the student is right now

The student's state (new, active, at risk, dormant, expert, mentor) is the question the rest of the engine keeps answering: which notification to send, which challenge to propose. If it is scattered across booleans such as is_active and has_mastery, sooner or later two booleans contradict each other and nobody knows which one is true. A state machine moves the problem into a table of transitions: pairs (starting state, event) that point to an arrival state, with an optional condition.

state_machine.py: transitions as data
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from enum import Enum, auto
from typing import Callable, Dict, List, Optional


class LearnerState(Enum):
    ONBOARDING = auto()
    ACTIVE = auto()
    AT_RISK = auto()
    DORMANT = auto()
    MASTERY = auto()
    MENTOR = auto()


class LearnerEvent(Enum):
    LESSON_COMPLETED = "lesson_completed"
    COURSE_COMPLETED = "course_completed"
    PEER_HELPED = "peer_helped"
    INACTIVE_7_DAYS = "inactive_7_days"
    INACTIVE_14_DAYS = "inactive_14_days"
    REACTIVATED = "reactivated"


@dataclass(frozen=True)
class LearnerContext:
    student_id: str
    state: LearnerState
    peers_helped: int = 0
    metadata: Dict = field(default_factory=dict)


@dataclass(frozen=True)
class Transition:
    source: LearnerState
    event: LearnerEvent
    target: LearnerState
    condition: Optional[Callable[[LearnerContext], bool]] = None


TRANSITIONS = [
    Transition(LearnerState.ONBOARDING, LearnerEvent.LESSON_COMPLETED, LearnerState.ACTIVE),
    Transition(LearnerState.ACTIVE, LearnerEvent.INACTIVE_7_DAYS, LearnerState.AT_RISK),
    Transition(LearnerState.AT_RISK, LearnerEvent.INACTIVE_14_DAYS, LearnerState.DORMANT),
    Transition(LearnerState.AT_RISK, LearnerEvent.REACTIVATED, LearnerState.ACTIVE),
    Transition(LearnerState.DORMANT, LearnerEvent.REACTIVATED, LearnerState.ACTIVE),
    Transition(LearnerState.ACTIVE, LearnerEvent.COURSE_COMPLETED, LearnerState.MASTERY,
               lambda ctx: ctx.metadata.get("score", 0) >= 90),
    Transition(LearnerState.MASTERY, LearnerEvent.PEER_HELPED, LearnerState.MENTOR,
               lambda ctx: ctx.peers_helped >= 5),
]
INDEX = {(t.source, t.event): t for t in TRANSITIONS}


def process_event(ctx, event, data=None, publish=print):
    """Returns a new context; the incoming one is left untouched."""
    transition = INDEX.get((ctx.state, event))
    if transition is None:
        return ctx                                   # event with no transition: ignored
    candidate = replace(ctx, metadata={**ctx.metadata, **(data or {})})
    if transition.condition and not transition.condition(candidate):
        return ctx                                   # condition not met
    publish({"type": "state_transition", "student_id": ctx.student_id,
             "from": ctx.state.name, "to": transition.target.name, "event": event.value,
             "at": datetime(2026, 3, 10, 9, 0, tzinfo=timezone.utc).isoformat()})
    return replace(candidate, state=transition.target)


if __name__ == "__main__":
    ctx = LearnerContext("s-42", LearnerState.ONBOARDING)
    ctx = process_event(ctx, LearnerEvent.LESSON_COMPLETED)
    print("state:", ctx.state.name)
    ctx = process_event(ctx, LearnerEvent.COURSE_COMPLETED, {"score": 84})
    print("after course at 84%:", ctx.state.name)
    ctx = process_event(ctx, LearnerEvent.COURSE_COMPLETED, {"score": 93})
    print("after course at 93%:", ctx.state.name)
    aiutato = process_event(ctx, LearnerEvent.PEER_HELPED)
    print("one help, peers_helped=0:", aiutato.state.name)
    ctx = replace(ctx, peers_helped=5)
    ctx = process_event(ctx, LearnerEvent.PEER_HELPED)
    print("peers_helped=5:", ctx.state.name)

# Output (executed):
# {'type': 'state_transition', 'student_id': 's-42', 'from': 'ONBOARDING', 'to': 'ACTIVE', 'event': 'lesson_completed', 'at': '2026-03-10T09:00:00+00:00'}
# state: ACTIVE
# after course at 84%: ACTIVE
# {'type': 'state_transition', 'student_id': 's-42', 'from': 'ACTIVE', 'to': 'MASTERY', 'event': 'course_completed', 'at': '2026-03-10T09:00:00+00:00'}
# after course at 93%: MASTERY
# one help, peers_helped=0: MASTERY
# {'type': 'state_transition', 'student_id': 's-42', 'from': 'MASTERY', 'to': 'MENTOR', 'event': 'peer_helped', 'at': '2026-03-10T09:00:00+00:00'}
# peers_helped=5: MENTOR

The point of the listing is INDEX: a dictionary that associates each (state, event) pair with its transition, so finding the answer to an event costs one lookup and not a chain of ifs. process_event does three things in order. If the pair does not exist it ignores the event (in the output, peer_helped from MASTERY with zero helps leaves the state as it is). If the condition fails it returns the context unchanged (the course closed with 84 does not lead to MASTERY, the one with 93 does). Only then does it publish the transition event and return a new context: LearnerContext is frozen, so no caller can alter it by mistake.

Two limits to know about. The condition for becoming a mentor reads peers_helped, but the machine does not increment it: whoever receives the event must do it, before calling the machine, which is why the listing sets it by hand. And the inactivity events (inactive_7_days, inactive_14_days) do not originate from an action by the student: you need a periodic job to generate them, otherwise no student will ever become "at risk". The listing publishes with print; in production the publish function writes to a bus such as Kafka or to an event log, but this article does not cover that.

XP and levels: why levels grow with the logarithm

Experience points (XP) have two jobs: give immediate feedback on every action and map the total onto a level. The simplest way is to make each level double. The level is then the base-2 logarithm of the total divided by 100, plus one: moving up a level costs twice the previous one, and the first levels arrive quickly while the later ones require real commitment. Whoever writes "logarithmic curve" means exactly this: it is the XP required that grow exponentially, and the level as a function of XP that is logarithmic.

xp_system.py: levels and multiplier
import math

XP_BASE = {"lesson": 50, "quiz_pass": 100, "quiz_perfect": 200, "course": 500}
MAX_LEVEL = 20


def level_for(total_xp):
    """Level 1 below 100 XP; then one level each time the total doubles."""
    if total_xp < 100:
        return 1
    return min(int(math.log2(total_xp / 100)) + 1, MAX_LEVEL)


def xp_for_level(level):
    return 0 if level <= 1 else 100 * 2 ** (level - 1)


def multiplier(streak_days, difficulty, optimal_hours=False):
    streak = min(streak_days * 0.05, 0.5)          # +5% a day, capped at +50%
    hard = max(0, (difficulty - 2) * 0.10)         # difficulty 2 = baseline
    hours = 0.20 if optimal_hours else 0.0
    return 1.0 + streak + hard + hours


def grant(activity, current_xp, streak_days, difficulty=2, optimal_hours=False):
    m = multiplier(streak_days, difficulty, optimal_hours)
    gained = int(XP_BASE[activity] * m)
    total = current_xp + gained
    return {"gained": gained, "multiplier": round(m, 2), "total": total,
            "level": level_for(total), "level_up": level_for(total) > level_for(current_xp)}


if __name__ == "__main__":
    for lv in (1, 2, 3, 4, 5, 10):
        print(f"level {lv}: from {xp_for_level(lv)} XP")
    print(grant("quiz_pass", current_xp=380, streak_days=7, difficulty=4, optimal_hours=True))
    print(grant("lesson", current_xp=0, streak_days=0))
    print("levels at 99, 100, 199, 200, 399, 400 XP:", [level_for(x) for x in (99, 100, 199, 200, 399, 400)])

# Output (executed):
# level 1: from 0 XP
# level 2: from 200 XP
# level 3: from 400 XP
# level 4: from 800 XP
# level 5: from 1600 XP
# level 10: from 51200 XP
# {'gained': 175, 'multiplier': 1.75, 'total': 555, 'level': 3, 'level_up': True}
# {'gained': 50, 'multiplier': 1.0, 'total': 50, 'level': 1, 'level_up': False}
# levels at 99, 100, 199, 200, 399, 400 XP: [1, 1, 1, 2, 2, 3]

Read the output carefully: level 1 spans 0 to 199 XP, not from 100. You can see it in the last two lines ([1, 1, 1, 2, 2, 3] for 99, 100, 199, 200, 399, 400 XP), because level_for returns 1 below 100 XP and again 1 between 100 and 199, and the second level starts at 200. This is consistent with xp_for_level but not with the comment "100 XP = level 1" that circulates in many examples. The MAX_LEVEL cap exists because level 10 already requires 51,200 XP and level 20 would exceed 50 million: a cap of 100, as you find around, is unreachable for anyone.

The multiplier adds three bonuses: +5% per streak day up to +50%, +10% for every difficulty point above level 2, +20% for studying in the optimal hours. In the example, a quiz worth 100 XP with a 7-day streak, difficulty 4 and an optimal hour is worth 1.75 times and gives 175 XP, which take the total from 380 to 555 and trigger level 3. The three parameters are design choices, not research results: the hourly bonus in particular should be dropped if you have no data to justify it, because it penalises those who study in the evening because of work. A multiplier that grows without a cap invites abuse, so the cap on the streak is there.

Idempotent badges: the constraint lives in the database, not in the code

The most frequent mistake is to check "does the student already have it?" and then insert. With two parallel requests, or with an event reprocessed after an error, both read "no" and insert: two badges. The solution is not a faster check but letting the database reject the duplicate. A primary key on (student_id, badge_id) makes the double insert impossible, and ON CONFLICT DO NOTHING turns the rejection into a silent action instead of an error.

badges.py: rules as data, assignment with ON CONFLICT
import sqlite3

BADGES = {
    "first_lesson": {"event": "lesson_completed", "count": 1},
    "week_streak": {"metric": "streak_days", "gte": 7},
    "perfect_quiz": {"event": "quiz_completed", "score": 100},
    "mentor": {"metric": "peers_helped", "gte": 10},
}


def rule_matches(rule, event, metrics):
    """A rule is data: it looks at the current event, or at a student metric."""
    if "event" in rule:
        if rule["event"] != event:
            return False
        if "count" in rule:
            return metrics.get("event_count", 0) >= rule["count"]
        if "score" in rule:
            return metrics.get("last_score", 0) >= rule["score"]
        return True
    if "metric" in rule:
        value = metrics.get(rule["metric"], 0)
        return (("gte" in rule and value >= rule["gte"])
                or ("eq" in rule and value == rule["eq"])
                or ("lte" in rule and value <= rule["lte"]))
    return False


AWARD_SQL = """INSERT INTO student_badges (student_id, badge_id)
               VALUES (:sid, :bid)
               ON CONFLICT (student_id, badge_id) DO NOTHING
               RETURNING badge_id"""


def award(conn, student_id, event, metrics):
    new = []
    for badge_id, rule in BADGES.items():
        if rule_matches(rule, event, metrics):
            row = conn.execute(AWARD_SQL, {"sid": student_id, "bid": badge_id}).fetchone()
            if row:                      # RETURNING returns no row if it was already there
                new.append(badge_id)
    conn.commit()
    return new


if __name__ == "__main__":
    conn = sqlite3.connect(":memory:")
    conn.execute("""CREATE TABLE student_badges (
        student_id TEXT NOT NULL, badge_id TEXT NOT NULL,
        PRIMARY KEY (student_id, badge_id))""")
    m = {"event_count": 1, "streak_days": 7}
    print("first time:", award(conn, "s-42", "lesson_completed", m))
    print("retry of the same event:", award(conn, "s-42", "lesson_completed", m))
    print("perfect quiz:", award(conn, "s-42", "quiz_completed", {"last_score": 100}))
    print("rows in table:", conn.execute("SELECT COUNT(*) FROM student_badges").fetchone()[0])

# Output (executed):
# first time: ['first_lesson', 'week_streak']
# retry of the same event: []
# perfect quiz: ['perfect_quiz']
# rows in table: 3

The listing separates two things. BADGES is a dictionary of rules: "an event with a threshold" or "a metric with a threshold", read by rule_matches, so a content manager adds a badge without touching the code. AWARD_SQL is the guarantee: the PostgreSQL documentation explains that ON CONFLICT DO NOTHING simply skips the insert on a violation, and that RETURNING returns only the rows actually inserted. It is this last detail that lets award know whether the badge is new and notify it only once.

In the output, the retry of the same event returns an empty list and the table stays at three rows. Two caveats. First: the listing runs on in-memory SQLite, which supports the same ON CONFLICT ... RETURNING syntax from version 3.35 but is not PostgreSQL, so it proves nothing about real concurrency, only that the application logic is correct. Second: the week_streak rule is a metric and is not tied to an event, so it is granted at the first opportunity in which it is evaluated, as the first line of the output shows; if that is not what you want, add an event to the rule. Any Redis cache of the list of badges must be invalidated after the commit, not before: otherwise a concurrent reader rebuilds it from the old data.

Windowed leaderboard: peers, not top of the class

A global leaderboard shows 10 names at the top and an enormous number at the bottom, and that is enough to discourage the students at the bottom. The alternative is to show the student with the neighbours immediately above and below them: always someone to catch and someone not to be overtaken by. Redis has a structure made for this: the sorted set, a set of elements ordered by score. According to the Redis documentation it is implemented with a skip list alongside a hash table, and adding or updating an element costs O(log N). ZINCRBY adds a delta to an element's score, creating it if missing.

leaderboard.py: sorted set, peer window and weekly key
import asyncio
from datetime import date


def key(scope, period="all-time", today=None):
    if period == "weekly":
        iso_year, iso_week, _ = (today or date.today()).isocalendar()
        return f"leaderboard:{scope}:{iso_year}:w{iso_week:02d}"
    return f"leaderboard:{scope}:{period}"


async def update_score(r, student_id, xp_delta, scopes, today=None):
    async with r.pipeline(transaction=True) as pipe:
        for scope in scopes:
            for period in ("all-time", "weekly"):
                pipe.zincrby(key(scope, period, today), xp_delta, student_id)
        await pipe.execute()


async def peer_window(r, student_id, scope, window=2):
    k = key(scope)
    rank = await r.zrevrank(k, student_id)           # 0 = first
    if rank is None:
        return []
    start = max(0, rank - window)
    rows = await r.zrevrange(k, start, rank + window, withscores=True)
    return [{"rank": start + i + 1, "student": s, "xp": int(x), "me": s == student_id}
            for i, (s, x) in enumerate(rows)]


class FakeRedis:
    """In-memory double with the semantics of only the commands used: it is NOT Redis."""
    def __init__(self):
        self.z = {}

    def pipeline(self, transaction=True):
        return FakePipe(self)

    def _order(self, k):                             # ascending score, then name
        return sorted(self.z.get(k, {}).items(), key=lambda kv: (kv[1], kv[0]))

    async def zrevrank(self, k, m):
        names = [n for n, _ in reversed(self._order(k))]
        return names.index(m) if m in names else None

    async def zrevrange(self, k, a, b, withscores=False):
        return list(reversed(self._order(k)))[a:b + 1]


class FakePipe:
    def __init__(self, r):
        self.r, self.ops = r, []

    async def __aenter__(self):
        return self

    async def __aexit__(self, *a):
        return False

    def zincrby(self, k, amount, member):
        self.ops.append((k, amount, member))

    async def execute(self):
        for k, amount, member in self.ops:
            d = self.r.z.setdefault(k, {})
            d[member] = d.get(member, 0) + amount


async def main():
    r = FakeRedis()
    for i, xp in enumerate((900, 700, 640, 610, 600, 580, 300, 120)):
        await update_score(r, f"s{i}", xp, ["course-algebra"], today=date(2026, 12, 31))
    print(key("course-algebra", "weekly", date(2026, 12, 31)))
    print(key("course-algebra", "weekly", date(2027, 1, 1)))
    d = date(2027, 1, 1)
    print("with date.year:", f"w{d.isocalendar()[1]} of year {d.year}")
    for row in await peer_window(r, "s4", "course-algebra", window=2):
        print(row)
    print("unknown:", await peer_window(r, "nessuno", "course-algebra"))

asyncio.run(main())

# Output (executed):
# leaderboard:course-algebra:2026:w53
# leaderboard:course-algebra:2026:w53
# with date.year: w53 of year 2027
# {'rank': 3, 'student': 's2', 'xp': 640, 'me': False}
# {'rank': 4, 'student': 's3', 'xp': 610, 'me': False}
# {'rank': 5, 'student': 's4', 'xp': 600, 'me': True}
# {'rank': 6, 'student': 's5', 'xp': 580, 'me': False}
# {'rank': 7, 'student': 's6', 'xp': 300, 'me': False}
# unknown: []

Here update_score updates in a single transaction (Redis MULTI/EXEC, requested by transaction=True) both the all-time leaderboard and the weekly one, in every scope: course, group, global. peer_window uses ZREVRANK, which gives the position starting from the top, and reads with ZREVRANGE the window around it. In the output, the student s4 is fifth and the window with width 2 runs from third to seventh place. Students tied on score are ordered in Redis lexicographically by name: the listing's double imitates this, but a leaderboard with many ties should add an explicit criterion.

The defect visible in the output is the weekly key. If you build it with date.today().year and the ISO week number, 1 January 2027 produces "2027, week 53", which does not exist: that day still belongs to week 53 of 2026. The two identical lines in the output show that using the ISO year, the first value of isocalendar(), keeps the week that straddles the year together. The listing runs on an in-memory double and not on Redis: the command syntax is the documented one, but I did not measure timings or behaviour under concurrency.

Streaks of consecutive days and time zones

A streak is a counter of consecutive calendar days with at least one activity. The trouble is "calendar day": the same instant is two different dates in two time zones. If the server decides with UTC time, a student in Tokyo who studies at 8:30 in the morning sees it attributed to the previous day, and can lose the streak without doing anything wrong. The zoneinfo module of the Python standard library converts the instant into the student's time zone; on systems without a time zone database, such as Windows, the documentation says to install the tzdata package.

streak.py: streak, grace days and time zone
from datetime import date, datetime, timedelta, timezone
from zoneinfo import ZoneInfo

FREEZE_MAX = 2


def today_for(tz_name, now_utc):
    """The calendar date in the student's time zone, not the server's."""
    return now_utc.astimezone(ZoneInfo(tz_name)).date()


def next_streak(last, today, current, freeze):
    """Returns (new_streak, remaining_freezes, outcome). Pure function: no Redis, no DB."""
    if last is None:
        return 1, freeze, "first activity"
    gap = (today - last).days
    if gap <= 0:
        return current, freeze, "already recorded today"
    if gap == 1:
        return current + 1, freeze, "streak extended"
    missed = gap - 1                       # whole days with no activity
    if missed <= freeze:
        return current + 1, freeze - missed, f"saved by {missed} freeze"
    return 1, freeze, "streak broken"


if __name__ == "__main__":
    # The same instant is two different dates
    istante = datetime(2026, 3, 10, 23, 30, tzinfo=timezone.utc)
    print("UTC  :", today_for("UTC", istante))
    print("Tokyo:", today_for("Asia/Tokyo", istante))
    print("New York:", today_for("America/New_York", istante))
    base = date(2026, 3, 10)
    for giorni, serie, freeze in ((0, 5, 2), (1, 5, 2), (2, 5, 2), (3, 5, 2), (4, 5, 2), (4, 5, 0)):
        print(f"last activity {giorni} days ago, streak {serie}, freeze {freeze} ->",
              next_streak(base - timedelta(days=giorni), base, serie, freeze))
    print("no activity:", next_streak(None, base, 0, FREEZE_MAX))

# Output (executed):
# UTC  : 2026-03-10
# Tokyo: 2026-03-11
# New York: 2026-03-10
# last activity 0 days ago, streak 5, freeze 2 -> (5, 2, 'already recorded today')
# last activity 1 days ago, streak 5, freeze 2 -> (6, 2, 'streak extended')
# last activity 2 days ago, streak 5, freeze 2 -> (6, 1, 'saved by 1 freeze')
# last activity 3 days ago, streak 5, freeze 2 -> (6, 0, 'saved by 2 freeze')
# last activity 4 days ago, streak 5, freeze 2 -> (1, 2, 'streak broken')
# last activity 4 days ago, streak 5, freeze 0 -> (1, 0, 'streak broken')
# no activity: (1, 2, 'first activity')

The listing separates the decision from the saving. next_streak is a pure function that receives the last date, today's date, the streak and the grace days (freeze) and returns the outcome, so it is tested without Redis or a database. The first three lines of the output show the same instant, 23:30 on 10 March 2026 in UTC, which is the 10th in New York and the 11th in Tokyo. The following lines follow the rule: if only one day is missing and you have a freeze, the streak continues and the freeze is consumed; with four days of absence and two freezes the streak breaks and does not consume the freezes, because they would be of no use.

It remains to decide where to keep the state. Redis is convenient for frequent reads but a key with an expiry loses data: if you store the freezes only there and the key expires, the student finds the maximum or zero depending on the code that reads. The source of truth must be the table in the database, with Redis as a cache rebuilt from it. The function writes nothing: whoever calls it updates the row with an INSERT ... ON CONFLICT DO UPDATE, the same pattern as the badges, which for PostgreSQL guarantees an atomic outcome of insert or update even under concurrency.

Where it hurts

The mistakes below are the most common on platforms that start from the points. None is exotic: each comes from treating the engine as a side dish, and each has a countermeasure already in the listings.

  • A single global leaderboard: at the bottom there is always the majority; use the peer window.
  • A badge for every trivial action: they devalue all of them; grant few, tied to milestones.
  • XP without rate limits: an automated client accumulates points forever; you need a cap per unit of time.
  • Progression in scattered booleans: two flags contradict each other; use the transition table.
  • Assignment with separate check and insert: a retry duplicates the badge; delegate to the database constraint.
  • Streak counted in UTC: it penalises those who live far from the Greenwich meridian; convert to the student's time zone.

The criterion that unites the six items is the same: every guarantee you entrust to the correct behaviour of the code will sooner or later be violated by a retry, a time zone or a bot. The guarantees that hold are those that live in a data structure: the UNIQUE constraint for badges, the transaction for the leaderboard, the transition table for the states. If you have to choose where to start, start with the idempotency of badges, because a mistake there shows immediately and cannot be corrected without apologising to the students. The rate limit on XP comes later, when you have real traffic to look at.

Frequently asked questions

Do I need a separate gamification engine or is a points table enough?

For a small course a table is enough. A separate engine is needed when the rules change often or must be edited by people who do not program: then rules as data and explicit states repay the complexity.

Why Redis for the leaderboard and not an SQL query with ORDER BY?

A query that sorts millions of rows is paid on every read. The Redis sorted set keeps the order at every update, with O(log N) cost according to the documentation, so reading a leaderboard window is cheap. For small volumes an indexed query is enough.

How do I prevent the same badge from being granted twice?

Put a primary key on student and badge and insert with ON CONFLICT DO NOTHING. The database discards the duplicate even with parallel requests, and RETURNING tells you whether the row is new.

What you can do now

You can model progression as a table of transitions, compute levels and multipliers predictably, grant badges exactly once thanks to a constraint, build a windowed leaderboard on a sorted set and count streaks in the student's time zone without losing them across the new year. The next step is to feed this engine with real study events: the pipeline described in Learning Analytics with xAPI and Kafka does that. If instead you want to work out which content to offer to those in the MASTERY state, start from Adaptive Learning Algorithms.

Before this article in the series: Personalized Tutoring with LLMs: RAG for Knowledge Grounding.

Sources

All listings were run with Python 3.14 in a temporary folder. The badge database is in-memory SQLite and the leaderboard uses an in-memory double of the Redis commands: the logic is verified, the real behaviour of PostgreSQL and Redis under load is not. The thresholds (XP, bonuses, optimal hours) 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