Skip to content
  • Our Product
    • Namazu Elements
      • What is Elements?
      • Why open source?
      • Docs
        • Namazu Elements in Five Minutes or Less
        • RESTful APIs Library
        • Security Model
        • Accessing the Web UI (CMS)

    Our Product

    A logomark with three layered rhombuses adorning the lettermark that says Elements in bold all-caps sans-serif letters.
    • What is Namazu Elements? Discover our easy-to-use backend network solution built for online games. Rapidly enables full-scale multiplayer games or online solo adventures.
    • Why open source? Is there a truly open source server backend for connected games? There is now. Download and run a local copy of Namazu Elements and try it for yourself.
    Download Namazu Elements

    Get started

    • Quick start Read our Elements 5-minute quick start guide
    • Documentation Read our developer docs for learning more about Elements
    • RESTful APIs A full list of core API specs for working with the Elements framework
    • Security An overview of the server-authoritative security model of Elements
    • Accessing the CMS Manage your game with ease via the Namazu Elements CMS.

    Co-development Reimagined

    • Best real-time game backends in 2026 If you're researching an alternative to your current backend solution, we've prepared a report of all of the backend solutions on the market in 2026 and how Namazu Elements compares.
      Co-dev

    Recent Posts

    • The watercolor-styled Namazu Studios logo over a giant namazu lurking in the depth
      Namazu Studios Featured in San Diego Business Journal
      22 Sep 2025 Press
    • Namazu Elements 3.1 Released – Service Layer Fixes, Secure APIs, and Steam Bug Fix
      22 Apr 2025 Release Notes
  • Case Studies
  • About Us
  • News
  • Services
  • Book a call
namazu-studios-logo
Book a call
Popular Search Roblox

Getting Started

  • Namazu Elements in Five Minutes or Less
  • Overview
  • Accessing the Web UI (CMS)
  • CMS Feature Overview

Fundamentals

  • Why You Need a Server (and What “Authoritative” Means)
  • Elements as a Game Runtime
  • Where Your Authoritative Code Runs
  • Lifecycles and Flows

General Concepts

  • Custom Elements
  • Data Models
  • Security Model
  • N-Tier Architecture

Namazu Elements Core Features

  • Email Service
  • Applications
  • Sessions
  • Users and Profiles
  • Digital Goods
  • Progress and Missions
  • Progress and Missions (3.4+)
  • Leaderboards
  • Matchmaking – Comprehensive Guide
  • Friends
  • Followers
  • Product Bundles and SKUs
  • Item Ledger
  • Receipts
  • Reward Issuances
  • Save Data
  • Metadata
  • Metadata (3.4+)
  • Queries
  • User Authentication / Sign In
    • What is a User?
    • Email Verification
    • User Authentication in Elements
    • Account Linking
    • Setting Up Twitch OIDC Login (Backend)
    • OIDC Login for Thick Clients (Browser Redirect Flow)
    • Auth Schemes
      • Auth Schemes
      • OAuth2
      • OIDC
  • Features
    • Web3
      • Wallets
      • Vaults
      • Omni Chain Support
      • Smart Contracts
        • Smart Contracts
  • Queries
    • Advanced Operators
    • Object Graph Navigation
    • Boolean Queries
    • Base Query Syntax
  • Advanced Operators
    • .name
    • .ref

Your Game Code - Adding Custom Elements

  • Custom Code Overview
  • Windows Setup
  • Mac OS Setup
  • Ubuntu Linux Setup
  • Element Anatomy: A Technical Deep Dive
  • Introduction to Guice and Jakarta in Elements
  • Structuring your Element
  • Events
  • Packaging an Element with Maven
  • Deploying an Element
  • Preparing for code generation
  • Properties
  • Websockets
  • RESTful APIs
  • Direct MongoDB Access (3.5+)
  • Building the Example Element: A Complete Walkthrough
  • Building the Kotlin Example Element: A Complete Walkthrough

Configuration

  • Configuring External URLs for Deployment
  • Matchmaking – Comprehensive Guide
  • Direct Database Access and Batch Configuration
  • Connecting Namazu Elements to a TLS-Enabled MongoDB Replica Set
  • Batch Samples
    • Mission Upload Bash Script Sample
    • Item Upload Bash Script Sample

RESTful APIs

  • Importing into Postman
  • RESTful APIs Library
  • Swagger and Swagger UI

Add-Ons

  • Crossplay
    • Crossfire Client Libraries (JVM & Browser)
    • Crossfire Protocol Reference
    • Crossfire: Custom Matchmaking Algorithms
    • Namazu Crossfire (Multiplayer)
    • Deploying Namazu Crossfire in your game
  • Roblox
    • Roblox Overview
    • Secure Player Authentication & Registration
    • Global Matchmaking
    • Roblox Security Best Practices
  • Container on Demand
    • Namazu Conductor
    • Namazu Conductor Admin API
    • Configuring Namazu Conductor Providers
  • Commerce
    • Stripe
      • Stripe
      • Configuring the Stripe Element
      • Stripe REST API Reference
      • Stripe REST API Reference

Game Engine & Client Support

  • Unity
    • Elements Unity Plugin
    • Unity Crossfire Plugin
  • Gamemaker
    • Incorporating GMEXT-Elements into a GameMaker Project

Troubleshooting

  • Common Issues with Docker
  • Local SDK
    • Unable to deploy application : dev.getelements.elements.sdk.exception.SdkElementNotFoundException
    • Could not load class : java.lang.NoClassDefFoundError
  • Namazu Elements Community Edition
    • Common Issues with Docker
    • Unable to deploy application : dev.getelements.elements.sdk.exception.SdkElementNotFoundException
    • Running in the IDE
      • Exception in monitor thread while connecting to server localhost:27017
      • Could not deployAvailableApplications Jetty server Failed to bind to /0.0.0.0:8080 Address already in use

Releases

  • 3.8 Release Notes
  • 3.7 Release Notes
  • 3.6 Release Notes
  • 3.5 Release Notes
  • 3.4 Release Notes
  • 3.3 Release Notes
  • 3.2 Release Notes
  • 3.1 Release Notes
View Categories
  • Home
  • Docs
  • Add-Ons
  • Crossplay
  • Crossfire: Custom Matchmaking Algorithms

Crossfire: Custom Matchmaking Algorithms

Est. read time: 6 min read

AI Doc Summarizer Doc Summary
AI Doc Summarizer Thinking Thinking

Namazu Crossfire ships two built-in matchmaking algorithms — a FIFO queue and a simple join-code flow — but both matching strategies are pluggable. This page walks through how the built-in algorithms actually work end-to-end, and what you get for free when you write your own (ratings-based matching, party/lobby systems, region-aware pools, and so on).

This assumes familiarity with the Crossfire Protocol Reference, in particular the four handshake flows (FIND/JOIN vs. CREATE/JOIN_CODE).


Two algorithm interfaces #

There are two Distinct extension points, corresponding to the two handshake flow pairs — they are not variants of each other, and a given implementation only serves one:

  • FindMatchmakingAlgorithm — serves FIND (initialize) and JOIN (resume). The built-in implementation is FIFOMatchmakingAlgorithm.
  • JoinCodeMatchmakingAlgorithm — serves CREATE (initialize) and JOIN_CODE (resume). The built-in implementation is SimpleJoinCodeMatchmakingAlgorithm.

Both extend the common MatchmakingAlgorithm<CreateT, ResumeT> contract:

  • initialize(request) — called for the “first contact” request (FIND or CREATE). Must be non-blocking and return a MatchHandle immediately.
  • resume(request) — called for a “second contact” request (JOIN or JOIN_CODE). Also non-blocking, also returns a MatchHandle.

The MatchPhase lifecycle #

Every MatchHandle tracks its own phase, independent of the connection’s ConnectionPhase:

READY → MATCHING → MATCHED → TERMINATED
MatchPhase state machine: READY to MATCHING to MATCHED to TERMINATED, with cancellation transitions to TERMINATED from READY and MATCHING

TERMINATED is absorbing — every transition first checks for it and no-ops if already there, so a handle can never come back to life once the player has disconnected or left. Transitions are otherwise strict and enforced by the state record itself: startMatching() requires READY, and reporting a result requires MATCHING; calling either out of order throws ProtocolStateException rather than silently doing nothing.

What AbstractMatchHandle gives you #

AbstractMatchHandle<RequestT> (in the util module) is the base class every concrete MatchHandle should extend. It owns the MatchPhase state machine in an AtomicReference and turns each public MatchHandle method into a phase-checked dispatch to one of six abstract hooks you implement:

  • onMatching(state) — do the actual work of finding or creating a match. This is the only hook every algorithm must supply itself; there’s no generic implementation of “how do I match.”
  • onResult(state, result) — called once you invoke setResult(...) from within onMatching, completing the handshake.
  • onLeaveMatch(state) — the player is leaving a match they were already matched into.
  • onOpenMatch(state) / onCloseMatch(state) / onEndMatch(state) — back the OPEN/CLOSE/END control messages. These don’t change MatchPhase themselves — a match can be opened and closed repeatedly while MATCHED.

Two of these dispatches are worth studying closely, because they demonstrate the updateAndGet vs. getAndUpdate distinction called out in the protocol reference:

  • startMatching() uses updateAndGet — it needs the resulting phase to decide whether to actually kick off onMatching, or just log if the handle was already terminated (e.g. the player disconnected before matching started).
  • leaveMatch() uses getAndUpdate — it needs the phase before the termination transition overwrote it, because the cleanup differs: a MATCHED handle has a real match/result to release (onLeaveMatch), while a still-MATCHING handle has nothing to release yet (falls through to a log-only default).

Inside onMatching, call the protected setResult(MultiMatch) once you’ve found or created the match — this is what drives the MATCHING → MATCHED transition and ultimately calls getRequest().success(this), which is what actually sends the handshake response and moves the connection into SIGNALING.

Skipping the boilerplate with StandardCancelableMatchHandle #

StandardCancelableMatchHandle<RequestT> (also in util) implements every hook except onMatching in terms of the standard MultiMatchDao operations, so most custom algorithms only need to extend it and write onMatching:

  • onEndMatch → DAO.endMatch(matchId)
  • onCloseMatch → DAO.closeMatch(matchId)
  • onOpenMatch → re-fetches the match, then DAO.openMatch(...)
  • onLeaveMatch → DAO.removeProfile(matchId, Profile), and deletes the match if that was the last Profile
  • onResult → getRequest().success(this)

Every DAO call in these hooks (other than onOpenMatch) is dispatched via getRequest().getServer().submit(...) so it runs off the calling thread — your onMatching override should follow the same pattern rather than blocking on database access directly.

Walkthrough: FIFOMatchmakingAlgorithm #

FIFOMatchmakingAlgorithm is the reference implementation to model a new FindMatchmakingAlgorithm on:

  1. initialize(request) returns a private inner FIFOMatchHandle, extending StandardCancelableMatchHandle<FindHandshakeRequest>.
  2. resume(request) returns a plain StandardJoinMatchHandle — a generic, protocol-level handle (not FIFO-specific) that re-looks-up the existing match by id and verifies the requesting Profile is a member. Reconnection logic doesn’t depend on how the match was originally formed, so any FindMatchmakingAlgorithm can reuse this class as-is for its resume().
  3. FIFOMatchHandle.onMatching submits work to the server executor: opens a transaction, calls MultiMatchDao.findOldestAvailableMultiMatchCandidate(configuration, profileId, ""); if nothing is available it creates a brand-new OPEN MultiMatch; either way it adds the requesting Profile and calls setResult(...).

A ratings-based or region-aware algorithm would follow the identical shape — swap step 3’s DAO query for your own candidate-selection logic (e.g. querying a rating Service and filtering candidates by rating window before falling back to creating a new match).

Walkthrough: SimpleJoinCodeMatchmakingAlgorithm #

The create/join-code flow differs from FIFO in a few instructive ways:

  • It exposes two deployment-configurable Element attributes — JOIN_CODE_LENGTH (default 4) and MAX_ATTEMPTS (default 2000) — rather than hardcoding join-code generation parameters.
  • initialize()‘s handle creates the match via a join-code-aware DAO overload, DAO.createMultiMatch(match, parameters), where parameters (a UniqueCodeDao.GenerationParameters) carries the code length/attempt budget along with the app config’s timeout/linger seconds.
  • It overrides newHandshakeResponse() on its handle to return a CreatedHandshakeResponse (populated with matchId, joinCode, profileId) instead of the default MatchedResponse. This is the pattern to copy any time your algorithm needs to hand extra data back to the client in the handshake response — MatchHandle‘s default newHandshakeResponse() only returns a bare MatchedResponse.
  • resume() (serving JOIN_CODE) uses StandardJoinCodeMatchHandle, whose onMatching looks the match up by join code (DAO.getMultiMatchByJoinCode(...)) and adds the joining Profile if it isn’t already a member — unlike FIFO, where Profile-adding only happens in initialize(), here it can also happen during resume() since that’s when a second player actually shows up.

Registering your algorithm #

Export your implementation with @ElementServiceExport and bind it in your Element’s Guice module. To make an algorithm selectable by name from a MatchmakingApplicationConfiguration.matchmaker reference (rather than only usable as your Element’s default), bind it twice — once unqualified and once under a @Named annotation — following the exact pattern Crossfire itself uses for FIFO and simple join-code:

@ElementServiceExport(value = FindMatchmakingAlgorithm.class)
@ElementServiceExport(value = FindMatchmakingAlgorithm.class, name = "RATING_WINDOW")
public class RatingWindowMatchmakingAlgorithm implements FindMatchmakingAlgorithm { /* ... */ }
bind(FindMatchmakingAlgorithm.class).to(RatingWindowMatchmakingAlgorithm.class);
bind(FindMatchmakingAlgorithm.class)
    .annotatedWith(named("RATING_WINDOW"))
    .to(RatingWindowMatchmakingAlgorithm.class);
expose(FindMatchmakingAlgorithm.class);
expose(FindMatchmakingAlgorithm.class).annotatedWith(named("RATING_WINDOW"));

The unqualified binding becomes the algorithm used whenever a MatchmakingApplicationConfiguration doesn’t specify a matchmaker; the named binding is what V1HandshakeHandler.algorithmFromConfiguration() resolves when a configuration explicitly references your algorithm by its ElementServiceReference name — see Custom Elements for background on cross-Element Service resolution.

What are your Feelings
Still stuck? How can we help?

How can we help?

Updated on August 14, 2026
Crossfire Protocol ReferenceNamazu Crossfire (Multiplayer)
Table of Contents
  • Two algorithm interfaces
  • The MatchPhase lifecycle
  • What AbstractMatchHandle gives you
  • Skipping the boilerplate with StandardCancelableMatchHandle
  • Walkthrough: FIFOMatchmakingAlgorithm
  • Walkthrough: SimpleJoinCodeMatchmakingAlgorithm
  • Registering your algorithm
  • Documentation
  • Terms of Service
  • Privacy Policy
  • Contact us
  • Linkedin
  • Join our Discord

Namazu Studios LLC is powered by Namazu Elements, an open source modular backend framework for connected games.

Namazu Elements
  • Download
  • About Elements
  • Open source
  • Documentation
  • Support
Namazu Studios
  • Case Studies
  • About Us
  • News
Best realtime game backends 2026
Get in Touch
  • info@namazustudios.com
  • Book a call
  • (619) 862-2890
  • Linkedin
  • Discord

©2008-2026 Namazu Studios. All Rights Reserved.