Neo XO app icon

Case study · Spring Boot + Android · 2019–2022

Neo XO

Tic-tac-toe, rebuilt as a modern Android game with a real online mode. Pick a nickname, invite anyone from the live lobby and play in real time, while my own Spring Boot service runs every match in parallel, with no cap on how many.

JavaSpring BootSpring Data JPAMariaDBDockerRESTConcurrencyAndroid SDKRoomOkHttpObjectAnimator
Google PlayOnline at scale Play the AI Code snippet
Online lobby with six players and invite buttons
Incoming invite with a countdown, Cancel and Accept

A complete tic-tac-toe game for Android with three ways to play, a custom animation library, and xo-api, a small Spring Boot service on my home server that runs the online lobby and every live match side by side.

Play online

A live lobby, invites with a countdown, real-time moves and rematches against anyone, from any phone, synced in about half a second.

Built to run in parallel

A stateless Spring Boot API. Every match is its own row in MariaDB, so matches never wait for each other. Tested with 1,000 at once.

Play offline too

An AI with three difficulty levels, or two players on one phone. Matches of 1 to 7 rounds and win statistics in a Room database.

∞parallel matches
1,000matches load-tested
0lost moves
500 msonline sync

THE IDEA

Everyone knows tic-tac-toe. Most apps for it feel like a school exercise: a plain grid, a hard-coded opponent, and nobody to play with.

Neo XO treats it as a real game. It has a soft, modern look, motion on every screen, an AI with three personalities, a match format with a score, and online play against anyone in the lobby. It is published on Google Play in English and Romanian, and it shows no ads.

TRY IT

This board plays exactly like the single-player mode in the app. The AI uses the same rules for each level, thinks for the same 1 second, and a coin toss decides who opens each round. You are X. Change the level or the match length to start a new match, and watch your statistics build up.

YOU 00 AI

AI is thinking

Difficulty

OVERALL STATS MEDIUM

WIN RATE 0%

WINS 0MATCHES 0LOSSES 0

THE AI

The AI does not search the game tree. Before each move it scans the 8 lines of the board, the three rows, three columns and two diagonals, and answers three questions: can I win now, must I block a line where X already has two, and is there a line I can build on?

The level decides how it uses the answers. That keeps it fast and easy to tune, and it makes each level feel different: Easy makes human mistakes, Medium never misses a threat, and Hard also plans ahead.

You Won dialog with the overall statistics
JAVASpPlayActivity · AI move, condensed
// every line is scanned first: can the AI win, must it block, can it build?
switch (matchDifficulty) {
case DIFFICULTY_EASY:
if (canWin) putO(OlistNo, OelemNo);
else if (isCheck) {
if (getNoOfSigns() < 4) putO(listNo, elemNo);
else if (rand.nextInt(3) < 2) putRandom();
else putO(listNo, elemNo);
} else putRandom();
break;
case DIFFICULTY_MEDIUM:
if (canWin) putO(OlistNo, OelemNo);
else if (isCheck) putO(listNo, elemNo);
else putRandom();
break;
case DIFFICULTY_HARD:
if (canWin) putO(OlistNo, OelemNo);
else if (isCheck) putO(listNo, elemNo);
else if (canMoveSmart) putO(smartOlistNo, smartOelemNo);
else putRandom();
break;
}

EASY

Easy

Takes a win when it sees one. It blocks early threats, but once the board fills up it blocks only 1 time in 3 and plays a random cell otherwise.

MEDIUM

Medium

Wins if it can and always blocks. Otherwise it plays a random cell, so it is solid but has no plan of its own.

HARD

Hard

Wins, blocks, and otherwise builds: it adds a second O to a line that holds one O and no X, setting up its next win.

SYSTEM ARCHITECTURE

Online play runs on xo-api, a Spring Boot REST service I wrote for the game. It runs in Docker on my home server, behind a Traefik reverse proxy with automatic HTTPS. The phones never talk to each other: every invite and every move is a request to the API, stored in MariaDB, and read back by the other player.

PLAYERSXO-API · DOCKERMARIADBPlayer AAndroid · OkHttpPlayer BAndroid · OkHttpREST controllers/lobby · /matchesServices@Transactional · JPACleanup@Scheduled · 5 minlobbyPresence · invitesmatchesBoard · turn · rematchHTTPS · TraefikJPA · JDBCMoves & statusesPolled state PLAYERSXO-API · DOCKERMARIADBPlayer AAndroid · OkHttpPlayer BAndroid · OkHttpREST controllers/lobby · /matchesServicesJPACleanupEvery 5 minlobbyPresencematchesBoard · turnHTTPS · TraefikJPA · JDBCMoves & statusesPolled state

Both players talk only to xo-api. The database is the single source of truth for every lobby and match

SPRING BOOT

Stateless service

No sessions, sockets or game threads. The service keeps nothing in memory, so a restart never loses a match, and many matches run side by side.

MARIADB

Spring Data JPA

Two entities, XoPlayer and XoMatch, with CRUD repositories. Every write runs in a @Transactional service method.

SCHEDULER

Self-cleaning

A @Scheduled job runs every 5 minutes and deletes players and matches that have not been updated for 5 minutes or more.

ACTUATOR

Health check

Spring Boot Actuator exposes the health endpoint. The app calls it first and shows the server as Online or Offline.

Two resources, one small contract

2 controllers · 12 endpoints · base path /xo-api · plus /actuator/health

lobbymatchesactuator
  • GET/actuator/healthIs the service up? Shown as Online or Offline
  • GET/lobby/playersEveryone in the lobby, with status and opponent
  • GET/lobby/players/{name}One player: status checks and invites
  • GET/lobby/players/namelistJust the nicknames
  • POST/lobby/players/post/jsonJoin, or change a status. The date is set to now
  • DELETE/lobby/players/{name}Leave the lobby
  • GET/matches/idListIds in use, to pick a free one
  • GET/matches/{id}The board, the turn and the status
  • POST/matches/post/jsonCreate a match or save a move
  • DELETE/matches/{id}Remove a finished match

THE LOBBY

Check the server

The online screen calls the health endpoint and shows the server as Online or Offline.

Pick a nickname

Names are upper-cased and must be unique. In the recording MARIA is taken, so the app says "Name already taken!".

Join the lobby

The player is posted as FREE. Players who are already in a match are hidden, so the list only shows people you can invite.

Watch it live

Three loops poll the server. When ALEX joins, he appears within a second and the count goes from 5 to 6.

1000 MS

Player list

Refreshed every 1 s. Each row has an INVITE pill, and a pulsing ring behind the list shows that the lobby is live.

500 MS

Own status

Polled every 500 ms. This is how the sender learns that an invite was accepted and which match to open.

200 MS

Incoming invites

Checked every 200 ms, so the invite dialog opens almost at once. After a decline, new invites are paused for 14 s.

TIMEOUT

Inactivity

After 5 minutes without an update, the app returns to the menu with "Disconnected due to inactivity", and the server cleans up the row.

THE INVITATION HANDSHAKE

Starting a match takes two phones, one server and no direct connection. The handshake is a short conversation through the lobby table: each player writes a status, and the other one reads it on its next poll. Both sides show a 10 second countdown, and anything other than an accept returns both players to FREE.

TWO PHONES · ONE INVITE

EDUARD · phone A
CRISTINA · phone B

Recorded on two phones against xo-api. EDUARD taps Invite, CRISTINA's phone shows the invite with its countdown about a second later, she accepts, and both phones open the same match.

POST INVITE_TO · INVITE_FROMGET own status · every 200 msINVITE_FROM · opponent AGET A · is the invite still open?GET matches/idList · lowest free idPOST match 7 · random first turnPOST A = START_MATCH-7-BA polls · both open match 7Player ASenderxo-apilobby · matchesPlayer BReceiverRequestResponse INVITE_TO / FROMGET my statusINVITE_FROMA still waiting?GET idListPOST match 7START_MATCH-7-BSTART_MATCH-7-BPlayer Axo-apiPlayer BRequestResponse

The invitation handshake. Every step is a plain HTTP call, and the lobby table holds the state in between

FREEINVITE_TOINVITE_FROMSTART_MATCH-7-BPLAYING

The lobby statuses. A decline, a cancel or the 10 second timeout sends both players back to FREE

The receiver does the heavy lifting. Before accepting, it re-reads the sender to make sure the invite is still open, so a cancelled or expired invite never starts a match.

It then picks the lowest free match id, creates the match with a random first turn, and writes START_MATCH-7-B to the sender: the match id and who plays first, packed into one status. The sender sees it within 500 ms, and both phones open the same match.

JAVAInviteFromDialog · accepting an invite
private void acceptInvite() {
int matchId = generateMatchId();
XoMatch xoMatch = new XoMatch(myName, playerWhoSentName);
xoMatch.setId(matchId);
xoMatch.setRandomFirstTurn();
xoMatch.setStatus(MATCH_STATUS_PLAYING);
// the sender is waiting for: START_MATCH-{id}-{firstTurn}
setOpponentStatusToStartMatch(matchId, xoMatch.getTurn());
startMpOnlinePlayActivity(xoMatch);
}

public int generateMatchId() {
List<String> idList = getIdList();
int id = 1;
while (idList.contains(String.valueOf(id))) {
id++;
}
return id;
}

THE ONLINE MATCH

A match is a single row in the matches table: the two players, whose turn it is, the nine cells b1 to b9, a status and the rematch flags. Only the player whose turn it is can write, which keeps the two phones from overwriting each other. While you wait, the app polls the match every 500 ms, and it checks the match status every 700 ms to notice a disconnect.

LIVE MATCH · SYNCED

EDUARD · plays X
CRISTINA · plays O

A real online round. Each move shows up on the other phone within about half a second, and both phones work out the gold winning line and the score from the same board.

JAVAMpOnlinePlayActivity · canPress, condensed
private boolean canPress(View view) {
boolean myTurn = myName.equals(xoMatch.getTurn());
boolean empty = ((Button) view).getText().toString().isEmpty();
if (myTurn && empty && !putSignTimerIsOn) {
// one move per 500 ms, even with a double tap
putSignTimerIsOn = true;
mHandler.postDelayed(() -> putSignTimerIsOn = false, 500);
return true;
}
return false;
}
JAVAXoMatchController · POST /matches/post/json
@PostMapping("/post/json")
public void addMatchJson(@RequestBody String xoMatchJson) {
XoMatch xoMatch = mapper.readValue(xoMatchJson, XoMatch.class);
xoMatch.setDate(LocalDateTime.now().toString());
// a move carries no status: keep the one already stored
if (StringUtils.isEmpty(xoMatch.getStatus())
|| "NULL".equalsIgnoreCase(xoMatch.getStatus())) {
XoMatch current = xoMatchService.getMatchById(xoMatch.getId());
xoMatch.setStatus(current.getStatus());
}
xoMatchService.persist(xoMatch);
}

MOVES

Turn ownership

A tap counts only on your turn, on an empty cell, and not within 500 ms of the last one. The move is posted and the turn passes over.

ROUNDS

Alternating starts

The first turn of the match is random. After that, the opening move alternates every round, so nobody keeps the advantage.

REMATCH

Rematch

Each player sets their own rematch flag. The other one sees "requested a rematch" and an Accept button. When both flags are set, a new match starts.

STATUS

Disconnects

Leaving sets the status to DISCONNECTED. The other phone shows "left the match", deletes the match and goes back to the lobby.

MATCH END · REMATCH

EDUARD · the winner
CRISTINA · the loser

The end of a first-to-3 match. Each phone shows its own result, CRISTINA asks for a rematch, EDUARD sees "requested a rematch" and a green Accept, and a new match starts on both phones.

ONLINE AT SCALE

The lobby is not one shared game room. Every match is an independent row, the service keeps nothing in memory, and no match ever touches another match's row. So matches never wait for each other, and nothing in the code limits how many run at once: the only limits are the server's threads and database connections.

You can see it in the recordings. While EDUARD and CRISTINA play, six other matches are running on the same server, and those players are hidden from the lobby until their match ends.

LIVE MATCHES · IN PARALLELXO-APIMATCHES TABLEmatch 1match 2match 3match 4match 5match 6match 7match 8match 9match 10match 11∞no fixed limitStatelessany matchid 1PLAYINGid 2PLAYINGid 3PLAYINGid 4PLAYINGid 5PLAYINGid 6PLAYINGid 7PLAYINGid 8PLAYINGid 9PLAYINGMoves & pollsJPARequestBoard state LIVE MATCHESXO-APIMATCHES TABLEmatch 1match 2match 3match 4match 5match 6match 7match 8∞no limitStatelessany matchid 1PLAYINGid 2PLAYINGid 3PLAYINGMoves & pollsBoard state

Every match is its own row. The service holds no match in memory, so matches never wait for each other, and nothing in the code caps how many run at once

Load test: up to 1,000 matches at once

Two simulated phones per match, polling exactly like the app: the board every 500 ms, the status every 700 ms, and a move on every turn. 60 seconds per run.

1,000parallel matches
2,000simulated phones
6,300requests per second
0lost moves
MatchesPhonesRequests / sMedianp95ErrorsLost moves
1002006481.0 ms3.8 ms00
2505001,6240.6 ms2.9 ms00
5001,0003,2630.5 ms1.3 ms00
1,0002,0006,3079.6 ms54 ms00

Run on one laptop against a local copy of xo-api with an embedded H2 database in place of MariaDB, so it shows how the design behaves, not production numbers. At 1,000 matches the single-threaded test client was the limit: the API used about 1.6 of 14 CPU cores. A first run at that size had 246 client time-outs (0.07%); the repeat had none. After every run, each phone checked that all of its moves were still on the board.

STATELESS

Share nothing

No sessions, sockets or game threads. Each request reads or writes one row and returns, so any of Tomcat's 200 worker threads can serve any match.

ISOLATION

One row per match

A move writes only its own match row, so parallel matches never lock each other. Writes are short @Transactional calls over a pool of 10 connections.

CONSISTENCY

One writer per turn

Inside a match, only the player whose turn it is may write. The server keeps the stored status, so a late move cannot undo a match end.

SCALE OUT

Room to grow

Because nothing lives in memory, more xo-api containers could run behind Traefik against the same database without changing the app.

Known limit: the phone that accepts an invite picks the lowest free match id. If two invites are accepted in the same instant, both phones could pick the same id. It never showed up in the load test, which creates its matches up front, and the fix is to let the database generate the id.

DATA MODEL

The whole online game fits in two tables. Every write refreshes the date column, which is what the cleanup job and the inactivity timeout both read.

Two tables, one row per player and per match

MariaDB · mapped with Spring Data JPA · schema kept in sync by Hibernate

lobbyXoPlayer
  • namevarchar'EDUARD'
  • statusvarchar'PLAYING'
  • opponentvarchar'ANA'
  • datevarchar'…T18:42:07'
matchesXoMatch
  • idint7
  • player1varchar'EDUARD'
  • player2varchar'ANA'
  • turnvarchar'ANA'
  • statusvarchar'PLAYING'
  • b1 … b9varchar'X' · 'O' · ''
  • rematch1, rematch2varchar'REQUESTED'
  • datevarchar'…T18:43:12'
GET/xo-api/matches/7
{
"id": 7,
"player1": "EDUARD", "player2": "ANA",
"turn": "ANA", "status": "PLAYING",
"b1": "X", "b2": "", "b3": "O",
"b4": "", "b5": "X", "b6": "",
"b7": "O", "b8": "", "b9": "",
"rematch1": "", "rematch2": "",
"date": "2022-05-14T18:43:12.519"
}

Moves are posted without a status. The server fills it in from the stored row, so a move can never undo a MATCH_END or DISCONNECTED written by the other phone.

Old rows are not a problem either. The scheduled cleanup runs every 5 minutes and removes anything that has been quiet for 5 minutes, which also covers phones that lost their connection without saying goodbye.

JAVAXoCleanupService · condensed
@Scheduled(cron = "0 */5 * ? * *")
public void startMatchCleanup() {
LocalDateTime now = LocalDateTime.now();
xoMatchService.getMatches().forEach(match -> {
LocalDateTime entryDate = LocalDateTime.parse(match.getDate());
if (entryDate.until(now, ChronoUnit.MINUTES) >= 5) {
xoMatchService.deleteById(match.getId());
}
});
}

MOTION

Every movement in the game comes from MyAnim, a small animation library I wrote on top of Android's ObjectAnimator. It has around 20 ready-made effects: pop, press, buzz, slide, zoom, fade, colour changes, a progress bar and a number count-down.

The recording shows the menu as it really runs: the logo pops in, the background slowly zooms, buttons shrink to 90% when pressed, and each screen slides its buttons in. On the board, signs zoom in with an overshoot, and a bad nickname makes the field buzz.

JAVAMyAnim · pop, condensed
public static void pop(View view) {
ObjectAnimator goUp = ObjectAnimator.ofPropertyValuesHolder(view,
PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f, 1.1f),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f, 1.1f));
goUp.setDuration(500);
ObjectAnimator goDown = ObjectAnimator.ofPropertyValuesHolder(view,
PropertyValuesHolder.ofFloat(View.SCALE_X, 1.1f, 1.0f),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.1f, 1.0f));
goDown.setDuration(500);
goDown.setStartDelay(500);
goUp.start();
goDown.start();
}

SCALE

Pop & press

pop grows a view to 110% and back to call for attention, like a rematch Accept. press dips a button to 90% and back.

TRANSLATE

Slide & buzz

Views slide in on X, Y or Z, and buzz shakes a view sideways to say no, with or without a rotation.

COLOUR

Colour

An ArgbEvaluator blends backgrounds and text colours, and a TransitionDrawable cross-fades button backgrounds.

TIMING

Interpolators

Each effect takes an interpolator: accelerate, decelerate, overshoot or anticipate, for a natural feel.

THE APP

The look is soft and bright: a pastel pink and blue background, rounded blue board lines, red X and blue O, and gold for the winning line. Text uses the geometric Moon typeface. The app runs in portrait on Android 8.0 and newer.

Neo XO home screen

MENU

Home

Singleplayer or Multiplayer, over a background that zooms in when the app opens.

Single player difficulty screen

AI

Difficulty

Easy, Medium or Hard, and a slider for a match length of 1 to 7.

Single player statistics dialog

STATS

Statistics

Win rate, wins, matches and losses for each level, stored in Room.

LOCAL

Two players

Two friends, one phone. X and O take turns, and the score keeps count.

UNDER THE HOOD

CLIENT

Android app

Java 17, target SDK 34. 7 activities and 13 dialogs, with OkHttp for the network and Handler loops for polling.

SERVER

xo-api

Spring Boot, Spring Data JPA, Actuator and Lombok on Java 8, packaged as a jar in a Docker container.

STORAGE

Room

One table holds matches, wins and losses for each level. The StatsDialog turns them into win rates.

I18N

Localisation

Every string is in English and Romanian, so the store listing is "X si 0 Online" in Romania.

RESULTS & NEXT STEPS

Results

A published game with three modes, an AI with three levels, local statistics, and live online matches on my own backend, any number of them in parallel. The server holds no state in memory, cleans up after itself, handled 1,000 simultaneous matches in a local load test, and has run in Docker next to this website. Version 3.0 removed all ads.

Future direction

Replace polling with WebSockets and STOMP, validate moves and pick match ids on the server, add optimistic locking to the match row, move xo-api to Spring Boot 3, and add a minimax level that never loses.