View as Markdown

How to build skill-based matchmaking (SBMM) in Nakama

In multiplayer games, players often have a better experience when grouped with others with similar skill profiles. A strict skill window can leave players waiting indefinitely if few opponents are nearby in rating, so a good matchmaker progressively widens that window the longer a player waits. In this guide, we’ll walk through how to write that kind of skill-based matchmaking logic in Nakama’s Go runtime.

Prerequisites #

This guide builds directly on Nakama’s default matchmaker. Read Matchmaker first for an overview of tickets, properties, queries, and how the matchmaker pool and pass cycle work.

Where this guide fits #

Matchmaking in Nakama is a repeating batch process, and it runs in six steps. The full sequence is covered in How matchmaking works:

  1. Your game client submits a ticket.
  2. Nakama adds the ticket to the pool.
  3. On a fixed timer, Nakama checks everyone currently waiting in the pool and forms whatever matches it can. This check is called a pass.
  4. Nakama notifies the matched players.
  5. Create the match.
  6. Join the match.

This guide is about step 3: write a custom matchmaker processor that widens a player’s search radius the longer their ticket waits.

Define your matchmaking rules #

Take a 1v1 arena duel game. Every player carries a skill rating, or MMR, and the matchmaker looks for an opponent close to that rating. The longer a player waits, the further out it’s willing to look.

For a player with skill rating MMR of 50, these are the acceptance bands we’d honor, from narrowest to widest:

  • Best: an opponent within 100 points, so a MMR of 0 to 150.
  • Second best: an opponent within 500 points, so a MMR of 0 to 550.
  • Third best: an opponent within 1000 points, so a MMR of 0 to 1050.
  • Last resort: anyone in the queue.
Diagram showing the acceptance bands for a player at MMR 50: best within 100 points, second best within 500, third best within 1000, last resort anyone
Acceptance bands for a player at MMR 50

Progressively expand the search with a matchmaker processor #

This guide customizes the matchmaking logic to widen the search server-side, which also keeps match selection authoritative: players can’t widen their own search radius or spoof a better match by tampering with the client.

To use your own logic for making the matches, you take over the pass via the RegisterMatchmakerProcessor function.

Register the function in main.go:

main.go
1
2
3
4
5
6
7
8
9
func InitModule(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, initializer runtime.Initializer) error {
    if err := initializer.RegisterMatchmakerProcessor(progressiveMatchmakerProcessor); err != nil {
        return err
    }
    return nil
}

func progressiveMatchmakerProcessor(ctx context.Context, logger runtime.Logger, db *sql.DB,
    nk runtime.NakamaModule, entries []runtime.MatchmakerEntry) [][]runtime.MatchmakerEntry

progressiveMatchmakerProcessor receives the whole pool of tickets inside entries and can determine exactly which players should match in each pass.

The processor runs once per matchmaker.interval_sec, 15 seconds by default, and you can set it to whatever suits your game. A ticket that goes unmatched is handed back to you on the next pass, a little older each time.

That gives us a natural way to implement progressive widening. The passes are already a clock, ticking once per interval. For example, with the interval set to 5 seconds, our match rules map onto the passes like this:

  • First pass: waited under 5s, search a MMR radius of 100. Best case.
  • Second pass: waited under 10s, widen to a radius of 500.
  • Third pass: waited under 15s, widen to a radius of 1000.
  • Fourth pass onwards: waited 15s or more, no limit, match with anyone. Last resort.
Chart showing a waiting ticket's search radius widening from ±100 to ±1000 MMR over four matchmaker passes, with an opponent 800 points away falling in range on pass 3
The search radius widens every pass

So the search radius can be expressed relative to how long a ticket waits to be matched:

main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Using a negative return value to mean no limit, the last resort band.
func searchRadius(waitSeconds float64) int {
    switch {
    case waitSeconds < 5:
        return 100
    case waitSeconds < 10:
        return 500
    case waitSeconds < 15:
        return 1000
    default:
        return -1
    }
}

You’ll call searchRadius for each ticket in the next section, when you build the sorted list of players.

Determine matches on each pass #

So far we’ve looked across passes, where each pass of the processor gives a waiting ticket a wider radius than the last. Now let’s zoom into a single one. In a single pass, Nakama hands you the whole pool of tickets at once. Your job is to decide which of them pair up.

Put simply, the logic is two steps: order the pool by skill rating, then pair adjacent players if the skill difference between them fits inside either one’s radius.

Step 1

Sort the pool by skill rating #

Before anything can be sorted, each entry needs its two numbers: the player’s rating, and the radius that comes from how long the ticket has waited.

main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
type player struct {
    entry  runtime.MatchmakerEntry
    mmr    int
    radius int
}

// Submitting [successive tickets](../../../concepts/multiplayer/matchmaker/#expanding-criteria)
// adds a new ticket rather than replacing the last, so a player can have more than one ticket in
// the pool at once. Build a map of one ticket per player, keeping only the most permissive one.
byUser := make(map[string]player, len(entries))

// The ticket's GetCreateTime is in nano second. Convert here before the wait time calculation.
nowNanos := time.Now().UTC().UnixNano()

for _, entry := range entries {
    // Both sides are UnixNano
    wait := time.Duration(nowNanos - entry.GetCreateTime())
    radius := searchRadius(wait.Seconds())
    userID := entry.GetPresence().GetUserId()

    if existing, ok := byUser[userID]; !ok || radius < 0 || (existing.radius >= 0 && radius > existing.radius) {
        byUser[userID] = player{
            entry:  entry,
            mmr:    int(entry.GetProperties()["mmr"].(float64)),
            radius: radius,
        }
    }
}

players := make([]player, 0, len(byUser))
for _, p := range byUser {
    players = append(players, p)
}

// Sort by MMR rating
slices.SortFunc(players, func(a, b player) int { return a.mmr - b.mmr })
Step 2

Pair adjacent players #

Now the list is ordered by skill rating, a player’s nearest possible opponent is already an immediate neighbor. You’ll walk the sorted list. Take the skill difference between each pair of neighbors. If either player accepts the difference, they match. If neither does, the sweep moves along one place and tries the next pair.

main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
var matches [][]runtime.MatchmakerEntry

for i := 0; i+1 < len(players); {
    a, b := players[i], players[i+1]
    mmrGap := b.mmr - a.mmr

    // We defined in the searchRadius function for a negative radius to mean
    // the last resort band: that player accepts anyone.
    aAccepts := a.radius < 0 || mmrGap <= a.radius
    bAccepts := b.radius < 0 || mmrGap <= b.radius

    if !aAccepts && !bAccepts {
        i++
        continue
    }

    matches = append(matches, []runtime.MatchmakerEntry{a.entry, b.entry})
    i += 2
}


return matches

You’ll return matched tickets. Entries not matched stay in the pool and come back next pass with a wider radius.

Full progressiveMatchmakerProcessor code #

Here’s the complete processor code in one place. See Trace the processor through two passes below for a worked example of it matching tickets.

main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// searchRadius is the whole schedule, in seconds of wait. A negative return means no limit, the
// last resort band.
func searchRadius(waitSeconds float64) int {
    switch {
    case waitSeconds < 5:
        return 100
    case waitSeconds < 10:
        return 500
    case waitSeconds < 15:
        return 1000
    default:
        return -1
    }
}

func progressiveMatchmakerProcessor(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, entries []runtime.MatchmakerEntry) [][]runtime.MatchmakerEntry {
    type player struct {
        entry  runtime.MatchmakerEntry
        mmr    int
        radius int
    }

    byUser := make(map[string]player, len(entries))

    // The ticket's GetCreateTime is in nano second. Convert here before the wait time calculation.
    nowNanos := time.Now().UTC().UnixNano()

    for _, entry := range entries {
        // Both sides are UnixNano.
        wait := time.Duration(nowNanos - entry.GetCreateTime())
        radius := searchRadius(wait.Seconds())
        userID := entry.GetPresence().GetUserId()

        // Keep only the most permissive ticket per player.
        if existing, ok := byUser[userID]; !ok || radius < 0 || (existing.radius >= 0 && radius > existing.radius) {
            byUser[userID] = player{
                entry:  entry,
                mmr:    int(entry.GetProperties()["mmr"].(float64)),
                radius: radius,
            }
        }
    }

    players := make([]player, 0, len(byUser))
    for _, p := range byUser {
        players = append(players, p)
    }

    // Sorting by MMR rating
    slices.SortFunc(players, func(a, b player) int { return a.mmr - b.mmr })

    var matches [][]runtime.MatchmakerEntry

    for i := 0; i+1 < len(players); {
        a, b := players[i], players[i+1]
        mmrGap := b.mmr - a.mmr

        // A negative radius, as defined, means the player accepts anyone.
        aAccepts := a.radius < 0 || mmrGap <= a.radius
        bAccepts := b.radius < 0 || mmrGap <= b.radius

        if !aAccepts && !bAccepts {
            i++
            continue
        }

        matches = append(matches, []runtime.MatchmakerEntry{a.entry, b.entry})
        i += 2
    }

    return matches
}

Things to watch out for #

Setting the threshold values #

A ticket is only ever evaluated once per interval, at ages spaced matchmaker.interval_sec apart. At a 5-second interval, a ticket might be checked at age 4s, then not again until age 9s, then 14s, skipping every age in between.

A single threshold at or above the interval isn’t enough. Thresholds also need to be spaced at least one interval apart from each other. With a 5-second interval, thresholds of 5, 6, and 7 seconds each clear the interval on their own, but a ticket checked at age 4s jumps straight to age 9s, crossing the 5 and 6-second thresholds in the same evaluation. The 6-second band never gets to apply by itself.

Validate ticket properties #

The processor above reads the rating with a bare type assertion, entry.GetProperties()["mmr"].(float64). Properties come from the client. Check the value in your production code:

1
2
3
4
5
mmr, ok := entry.GetProperties()["mmr"].(float64)
if !ok {
    logger.WithField("ticket", entry.GetTicket()).Warn("ticket has no usable mmr, skipping")
    continue
}

Trace the processor through two passes #

Take a pool of three. The processor interval is 5 seconds. In the trace below, i is the position in the sorted list sweep.

1
2
3
4
5
sorted by MMR: 400    1200   3000
waited:        10s    5s     10s
search radius: 1000   500    1000
               └───800───┘         i=0, gap 800, matched
                             3000  i=2, no neighbor left, stays in the pool

The 400-MMR player has waited two intervals, so their current search radius becomes 1000. The 800 point gap between this player and the 1200-MMR player is acceptable for the 400 player. The 1200-MMR player queued one interval ago, is still on a smaller acceptance radius of 500, and refuses that gap. Since in our logic acceptance is one-sided, the match forms.

The 3000-MMR player is left over in this pass. Five seconds later the next pass runs. The 3000 ticket has now waited 15s, which puts it in the last resort band, so it accepts anyone. Two fresh tickets have joined the pool since, both on the tightest radius because they’ve barely waited:

1
2
3
4
5
sorted by MMR: 180    700    3000
waited:        0s     0s     15s
search radius: 100    100    any
               └──520───┘                 i=0, neither accepts, refused, i++
                      └──2300───┘         i=1, 3000 accepts anyone, matched

At i=0 the two new tickets are 520 points apart and both are still on a radius of 100, so neither accepts and the sweep moves along one place rather than stopping. At i=1 the gap is far larger, 2300 points, and it matches anyway, because the 3000 player has run out of patience and will take any opponent.