diff options
| author | Arne Rief <riearn@proton.me> | 2026-02-13 21:04:35 +0100 |
|---|---|---|
| committer | Arne Rief <riearn@proton.me> | 2026-02-13 21:04:35 +0100 |
| commit | 50c0b1e5650bd1e8bc853d9a5520067d37860673 (patch) | |
| tree | 314b10bcaa9da224e16e1fbaa9b753db236466c7 /backend/src/simulation/robotMovementSimulator.ts | |
| parent | 44b0ea903dd35bae26aa5a167a2a04f157f5f53b (diff) | |
Better caching during simulation
Diffstat (limited to 'backend/src/simulation/robotMovementSimulator.ts')
| -rw-r--r-- | backend/src/simulation/robotMovementSimulator.ts | 27 |
1 files changed, 23 insertions, 4 deletions
diff --git a/backend/src/simulation/robotMovementSimulator.ts b/backend/src/simulation/robotMovementSimulator.ts index 2299f43..d3a2564 100644 --- a/backend/src/simulation/robotMovementSimulator.ts +++ b/backend/src/simulation/robotMovementSimulator.ts @@ -1,6 +1,7 @@ import { QueryResult } from "pg"; import { Server } from "socket.io"; import db from "../database/postgres.js"; +import redisClient from "../database/redis.js"; import { Robot, RobotPosition, @@ -8,6 +9,9 @@ import { SimulationResponse, } from "../types/robot.js"; +const CACHE_TTL = 10; +const ROBOTS_CACHE_KEY = "allMyRobots"; + // Coordinates for the boundaries of the frontend map const LEIPZIG_AREA = { WEST: 12.22, @@ -70,10 +74,19 @@ async function updateRobotPositions(io: Server) { try { client = await db.connect(); - const allRobotsQuery: QueryResult<Robot> = await client.query( - "SELECT * FROM robots ORDER BY id;" - ); - const allRobots = allRobotsQuery.rows; + let allRobots; + const cachedData = await redisClient.get(ROBOTS_CACHE_KEY); + + // Check Redis for cached data, otherwise query database + if (cachedData) { + allRobots = JSON.parse(cachedData); + } else { + const allRobotsQuery: QueryResult<Robot> = await client.query( + "SELECT * FROM robots ORDER BY id;" + ); + + allRobots = allRobotsQuery.rows; + } // Update database await client.query("BEGIN"); @@ -142,6 +155,12 @@ async function updateRobotPositions(io: Server) { await client.query("COMMIT"); + // Keep robots in Redis cache indefinitely while simulation is running to avoid db query on every tick + // Once the simulation stops, keep the cache alive for 10 seconds + await redisClient.set(ROBOTS_CACHE_KEY, JSON.stringify(updatedRobots), { + EX: movingRobots.size === 0 ? CACHE_TTL : undefined, + }); + // Websocket broadcast, make sure robots stay in correct order updatedRobots.sort((a, b) => a.id - b.id); |
