Building a Production-Grade Online Exam Anti-Cheating System with Java 21 & Spring Boot
This article details the design of a scalable online exam anti-cheating system using Java 21, Spring Boot, MySQL, Redis, and WebSocket, covering identity verification, session management, random paper generation, screen-switch detection, heartbeat monitoring, answer versioning, server-side timing, risk-based anomaly analysis, and deployment architecture for 5000 concurrent examinees.
Reading font

1. Separate Authentication Flows for Platform Login and Exam Hall Entry
A user logged into the exam platform does not guarantee the person at the keyboard is the actual candidate. Relying only on an Access Token allows device sharing. Therefore, a dedicated exam admission flow is required:
User logs into platform
↓ Check exam eligibility
↓ Create admission challenge
↓ Liveness detection & face match
↓ Verify exam device
↓ Create independent exam session
↓ Load paper & start timerFace verification reduces impersonation risk. The backend orchestrates the flow; feature extraction, liveness, and similarity scoring are delegated to a trusted biometric service. The server generates a one-time challengeId; after client-side face check, the backend obtains the result from the biometric service rather than trusting a client-sent facePassed=true.
public record ExamAdmission(
long examId,
long candidateId,
String challengeId,
String deviceKeyId,
Instant expiresAt
) {}public record FaceVerificationResult(
String requestId,
String challengeId,
boolean livenessPassed,
boolean matched,
double score,
String modelVersion
) {}The verification service must confirm the result belongs to the current candidate, challenge, device, and that the challenge is unused and unexpired. For low-stakes corporate training, face verification can be optional; for high-stakes exams, it is mandatory before start and may be repeated per proctoring rules. False negatives (poor lighting, camera quality, model error) require a retry or manual override path.
2. Allow Multi-Device Login but Enforce a Single Active Exam Session
Restricting the entire account to one device harms normal platform usage. Instead, allow multi-device login but create an isolated exam session per exam. A candidate can view materials on a phone while taking the exam on a laptop, but only one active answering session per exam.
Exam attempt table:
CREATE TABLE exam_attempt (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
exam_id BIGINT NOT NULL,
candidate_id BIGINT NOT NULL,
attempt_no INT NOT NULL DEFAULT 1,
status VARCHAR(32) NOT NULL,
active_session_id VARCHAR(64),
session_epoch BIGINT NOT NULL DEFAULT 0,
device_key_id VARCHAR(128),
started_at DATETIME(3),
deadline_at DATETIME(3),
submitted_at DATETIME(3),
submit_type VARCHAR(32),
policy_version VARCHAR(32) NOT NULL,
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_exam_attempt (exam_id, candidate_id, attempt_no),
INDEX idx_exam_timeout (status, deadline_at)
);Key fields: active_session_id (current valid session) and session_epoch (session generation). Each authorized device switch increments the epoch, invalidating the old device's credentials immediately.
public record ExamSession(
long attemptId,
long candidateId,
String sessionId,
long sessionEpoch,
String deviceKeyId,
Instant deadline
) {}Example: initial session epoch=1 on desktop. After approved switch to backup device, new session epoch=2. The old device's JWT becomes useless for answer submission.
Core validation logic:
public void validateSession(ExamAttempt attempt, ExamSession session) {
if (attempt.getCandidateId() != session.candidateId()) {
throw new ExamAccessDeniedException();
}
if (!Objects.equals(attempt.getActiveSessionId(), session.sessionId())) {
throw new ExamSessionInvalidException();
}
if (attempt.getSessionEpoch() != session.sessionEpoch()) {
throw new ExamSessionExpiredException();
}
if (!Objects.equals(attempt.getDeviceKeyId(), session.deviceKeyId())) {
throw new ExamDeviceMismatchException();
}
}Device identity must be more than a client-generated string; for high-security exams use client-held device keys with server-challenge signatures. Fingerprints, User-Agent, and IP are only auxiliary risk signals. Answer submission and device switching must share the same database concurrency control to prevent race conditions where an old device passes validation just as a new device takes over.
3. Random Paper Generation for 5000 Concurrent Examinees
Randomized papers are a practical anti-cheating measure. If all 5000 candidates receive identical questions in the same order, communication defeats other controls. The generator supports random selection, question-order shuffling, option-order shuffling, and knowledge-point/difficulty quotas.
Paper generation rules:
public record QuestionRule(
QuestionType type,
String knowledgePoint,
int difficulty,
int count
) {}
public enum QuestionType {
SINGLE_CHOICE, MULTIPLE_CHOICE, TRUE_FALSE, SHORT_ANSWER
}Example configuration:
Single choice, easy: 10
Single choice, medium: 15
Single choice, hard: 5
Multiple choice, medium: 10
True/false, easy: 10
Java implementation using SecureRandom and a usedIds set to avoid duplicates across rules:
@Service
public class PaperGenerateService {
private final SecureRandom random = new SecureRandom();
public List generate(List rules, List questionBank) {
Set usedIds = new HashSet<>();
List selected = new ArrayList<>();
for (QuestionRule rule : rules) {
List candidates = questionBank.stream()
.filter(q -> q.type() == rule.type())
.filter(q -> q.difficulty() == rule.difficulty())
.filter(q -> Objects.equals(q.knowledgePoint(), rule.knowledgePoint()))
.filter(q -> !usedIds.contains(q.id()))
.collect(Collectors.toCollection(ArrayList::new));
if (candidates.size() < rule.count()) {
throw new IllegalStateException("Insufficient questions for rule");
}
Collections.shuffle(candidates, random);
for (int i = 0; i < rule.count(); i++) {
Question question = candidates.get(i);
usedIds.add(question.id());
selected.add(question);
}
}
Collections.shuffle(selected, random);
List paper = new ArrayList<>();
for (int i = 0; i < selected.size(); i++) {
Question question = selected.get(i);
List options = new ArrayList<>(question.options());
if (question.shuffleOptionsAllowed()) {
Collections.shuffle(options, random);
}
paper.add(new PaperQuestion(question.id(), i + 1, options));
}
return paper;
}
}For large question banks, avoid loading the entire bank into memory; pre-build candidate sets by type/knowledge/difficulty or pre-generate papers before the exam. Options with fixed semantics (e.g., "All of the above") must not be shuffled. Persist the generated paper snapshot:
CREATE TABLE exam_paper_question (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
attempt_id BIGINT NOT NULL,
question_id BIGINT NOT NULL,
question_version BIGINT NOT NULL,
question_snapshot JSON NOT NULL,
option_order JSON,
score DECIMAL(8,2) NOT NULL,
sort_order INT NOT NULL,
UNIQUE KEY uk_paper_question (attempt_id, question_id)
);This ensures a reconnecting candidate receives the same paper. Grading must use stable option IDs, not position (A/B), because correct options appear at different positions across papers. Fairness note: difficulty labels alone don't guarantee equal difficulty; high-stakes exams should use calibrated banks or equated forms.
4. Detecting Browser Tab Switches on the Server Side
The Page Visibility API emits visibilitychange events when a user switches tabs, minimizes the window, or switches apps on mobile. The client queues events locally and sends them via a buffer (with sendBeacon fallback for unload).
document.addEventListener('visibilitychange', () => {
const event = {
eventId: crypto.randomUUID(),
attemptId: currentAttemptId,
sessionEpoch: currentSessionEpoch,
type: document.hidden ? 'PAGE_HIDDEN' : 'PAGE_VISIBLE',
clientTime: new Date().toISOString()
};
examEventQueue.enqueue(event);
});Events are sent as independent signals, not immediate cheat verdicts. The backend defines a unified event model:
public enum ExamEventType {
PAGE_HIDDEN, PAGE_VISIBLE, FULLSCREEN_EXIT,
CAMERA_DISCONNECTED, HEARTBEAT_TIMEOUT,
DEVICE_SWITCH_REQUEST, FACE_VERIFICATION_FAILED,
MULTIPLE_FACES_DETECTED, COPY_ATTEMPT, PASTE_ATTEMPT
}Database schema:
CREATE TABLE exam_behavior_event (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
event_id VARCHAR(64) NOT NULL,
attempt_id BIGINT NOT NULL,
session_epoch BIGINT NOT NULL,
event_type VARCHAR(50) NOT NULL,
event_source VARCHAR(32) NOT NULL,
client_time DATETIME(3),
server_time DATETIME(3) NOT NULL,
event_detail JSON,
created_at DATETIME(3) NOT NULL,
UNIQUE KEY uk_exam_event (attempt_id, event_id),
INDEX idx_attempt_event (attempt_id, server_time)
);Client-reported events (tab switch, copy/paste) and server-observed events (session epoch expiry, deadline, heartbeat gaps) are stored separately because their trust levels differ. A missing client event doesn't prove the candidate stayed on the page; a single tab switch doesn't prove cheating (OS notifications, accessibility tools, accidental hotkeys). Browsers cannot reliably monitor all running software; screen capture requires user consent. Thus, tab-switch detection is one input to anomaly analysis, not a sole verdict.
5. Heartbeat and Real-Time Proctoring with Redis and WebSocket
With 5000 candidates sending heartbeats every 15 seconds, average ~333 requests/second. Writing each to MySQL would cause unnecessary load. Redis holds the latest heartbeat state; MySQL persists only anomalies.
public record ExamHeartbeat(
long attemptId,
long sessionEpoch,
long sequence,
boolean cameraAvailable,
boolean pageVisible
) {}Heartbeat service validates the session and updates Redis with a 60-second TTL:
@Service
public class ExamHeartbeatService {
private final StringRedisTemplate redisTemplate;
public ExamHeartbeatService(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void heartbeat(ExamSession session, ExamHeartbeat heartbeat) {
if (session.attemptId() != heartbeat.attemptId()
|| session.sessionEpoch() != heartbeat.sessionEpoch()) {
throw new ExamSessionInvalidException();
}
String key = "exam:heartbeat:" + session.attemptId() + ":" + session.sessionEpoch();
redisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis()), Duration.ofSeconds(60));
}
}In clustered deployments, use a Lua script to atomically verify session epoch and heartbeat sequence, preventing stale heartbeats from overwriting current state. A Redis Sorted Set indexes next heartbeat deadlines:
Key: exam:heartbeat:deadline
Member: attemptId + sessionEpoch
Score: next heartbeat deadline timestampA background job fetches expired entries, re-validates the session and latest heartbeat time, and emits a HEARTBEAT_TIMEOUT event if confirmed. It tracks anomaly windows to avoid duplicate events for a single outage. Proctoring dashboards receive real-time updates via WebSocket:
public record ProctoringEvent(
long examId,
long attemptId,
ExamEventType eventType,
String riskLevel,
Instant occurredAt
) {}Heartbeat loss ≠ cheating; mobile, campus, and home networks often have brief drops. The system prioritizes reconnection and uses duration plus other evidence before escalating.
6. Answer Auto-Save: Preventing Old Answers from Overwriting New Ones
Losing an hour of answers due to a network/server failure is unacceptable. Answers are saved per-question with a version number, using client-side debouncing.
{
"attemptId": 10086,
"paperQuestionId": 30001,
"answer": ["option-3"],
"answerVersion": 8,
"sessionEpoch": 2
}If a candidate changes from A (version 7) to C (version 8), network reordering could deliver version 8 first, then version 7. A naive UPDATE would store the stale answer A. Hence version control is essential.
CREATE TABLE exam_answer (
attempt_id BIGINT NOT NULL,
paper_question_id BIGINT NOT NULL,
answer_content JSON NOT NULL,
answer_version BIGINT NOT NULL DEFAULT 0,
writer_epoch BIGINT NOT NULL DEFAULT 0,
updated_at DATETIME(3) NOT NULL,
PRIMARY KEY (attempt_id, paper_question_id)
);writer_epochhandles device switches: new device's writes take precedence over old device's; within the same session, answer version increments.
Core save logic (with row-level lock on exam_attempt):
@Service
public class ExamAnswerService {
private final ExamAttemptMapper attemptMapper;
private final ExamAnswerMapper answerMapper;
private final ExamSessionValidator sessionValidator;
private final Clock clock;
public ExamAnswerService(ExamAttemptMapper attemptMapper,
ExamAnswerMapper answerMapper,
ExamSessionValidator sessionValidator,
Clock clock) {
this.attemptMapper = attemptMapper;
this.answerMapper = answerMapper;
this.sessionValidator = sessionValidator;
this.clock = clock;
}
@Transactional
public AnswerSaveResult save(ExamSession session, SaveAnswerCommand command) {
ExamAttempt attempt = attemptMapper.lockById(session.attemptId());
sessionValidator.validateSession(attempt, session);
if (attempt.getStatus() != ExamStatus.IN_PROGRESS) {
throw new ExamAlreadySubmittedException();
}
if (!clock.instant().isBefore(attempt.getDeadlineAt())) {
throw new ExamTimeExpiredException();
}
ExamAnswer existing = answerMapper.findByQuestion(attempt.getId(), command.paperQuestionId());
if (existing == null) {
throw new InvalidPaperQuestionException();
}
boolean newer = session.sessionEpoch() > existing.getWriterEpoch()
|| (session.sessionEpoch() == existing.getWriterEpoch()
&& command.answerVersion() > existing.getAnswerVersion());
if (!newer) {
return AnswerSaveResult.from(existing);
}
answerMapper.update(attempt.getId(), command.paperQuestionId(),
command.answer(), command.answerVersion(), session.sessionEpoch());
return new AnswerSaveResult(command.paperQuestionId(),
command.answerVersion(), session.sessionEpoch(), command.answer());
}
}attemptMapper.lockById()uses SELECT ... FOR UPDATE. Answer save, device switch, and submit all lock the same attempt row, preventing a submit transaction from racing with a late answer update. Unacknowledged client requests retry with the same version; already-saved answers are not overwritten. The client should also cache unconfirmed answers in IndexedDB, syncing on reconnect. However, after the deadline, normal answer endpoints must reject writes; network incidents require a formal proctoring review process.
7. Server-Side Exam Timing and Automatic Submission
Client-side timers are unreliable: background tabs throttle timers, closing the page kills them. The server owns the clock.
Instant startedAt = clock.instant();
Instant personalDeadline = startedAt.plus(Duration.ofMinutes(90));
Instant deadline = personalDeadline.isBefore(exam.getEndAt()) ? personalDeadline : exam.getEndAt();The client's countdown is merely a display of the server-provided deadline. Every answer save, session change, and manual submit re-checks status and deadline.
public enum ExamStatus {
CREATED, IN_PROGRESS, SUBMITTED, GRADING, GRADED, CANCELLED
}Auto-submit scans for overdue IN_PROGRESS attempts:
SELECT id FROM exam_attempt
WHERE status = 'IN_PROGRESS'
AND deadline_at <= UTC_TIMESTAMP(3)
ORDER BY deadline_at, id
LIMIT 200;Submit logic (shared by manual and auto submit):
@Transactional
public SubmitResult submit(long attemptId, ExamSession session, SubmitType submitType) {
ExamAttempt attempt = attemptMapper.lockById(attemptId);
if (submitType == SubmitType.MANUAL) {
sessionValidator.validateSession(attempt, session);
}
if (attempt.isSubmitted()) {
return SubmitResult.from(attempt);
}
if (attempt.getStatus() != ExamStatus.IN_PROGRESS) {
throw new InvalidExamStatusException();
}
Instant now = clock.instant();
if (submitType == SubmitType.TIMEOUT && now.isBefore(attempt.getDeadlineAt())) {
throw new ExamNotExpiredException();
}
SubmitType effectiveType = now.isBefore(attempt.getDeadlineAt()) ? submitType : SubmitType.TIMEOUT;
attemptMapper.markSubmitted(attemptId, effectiveType, now);
outboxMapper.insert(ExamSubmittedEvent.of(attemptId));
return new SubmitResult(attemptId, effectiveType, now);
}Only trusted background tasks may invoke auto-submit; clients cannot pass SubmitType.TIMEOUT to bypass session validation. Because manual submit, auto-submit, and answer save all lock the same attempt row, a last-second manual submit and a concurrent auto-submit produce only one valid result. An Outbox event triggers asynchronous grading, avoiding blocking the submit response.
8. Explainable Risk Analysis Instead of Simple Counters
Rules like "three tab switches = auto-submit" or "one camera failure = cheat" are easy to implement but prone to false positives. Convert diverse anomalies into risk events, combining frequency, duration, evidence source, and verification results.
Example risk rules (scores are configurable per exam stakes):
Short tab switch: 5 points → warn candidate
Long page absence: 10 points → record anomaly
Extended heartbeat loss: 5 points → check network
Unauthorized device switch: 25 points → block new device
Persistent camera unavailability: 15 points → request recovery or manual check
Face re-verification failure: 30 points → request re-verification
Configurable rule engine:
public interface ExamRiskRule {
boolean supports(ExamEventType type);
RiskDecision evaluate(ExamBehaviorEvent event, RiskContext context);
}
public record RiskDecision(
String ruleCode,
int score,
String reason,
RiskAction action
) {}
public enum RiskAction { RECORD, WARN, REQUIRE_REVERIFY, REQUIRE_MANUAL_REVIEW }Tab-switch rule evaluates on PAGE_VISIBLE using paired hidden duration:
@Component
public class PageHiddenRiskRule implements ExamRiskRule {
@Override
public boolean supports(ExamEventType type) {
return type == ExamEventType.PAGE_VISIBLE;
}
@Override
public RiskDecision evaluate(ExamBehaviorEvent event, RiskContext context) {
Duration hiddenDuration = context.completedHiddenDuration();
if (hiddenDuration == null) {
return new RiskDecision("PAGE_HIDDEN_UNKNOWN", 0,
"Page hidden duration unknown", RiskAction.RECORD);
}
long seconds = hiddenDuration.toSeconds();
if (seconds >= 60) {
return new RiskDecision("LONG_PAGE_HIDDEN", 10,
"Extended absence from exam page", RiskAction.WARN);
}
return new RiskDecision("SHORT_PAGE_HIDDEN", 5,
"Brief absence from exam page", RiskAction.RECORD);
}
}Durations come from paired events; client timestamps are marked as unverified. The engine caps cumulative scores per anomaly type to prevent a single network glitch from generating dozens of heartbeat timeouts and pushing a candidate into high risk. Final risk report example:
{
"attemptId": 10086,
"riskScore": 35,
"riskLevel": "MEDIUM",
"reasons": [
"Multiple page exits",
"One unauthorized device switch request"
],
"decision": "REQUIRE_MANUAL_REVIEW",
"policyVersion": "2026.11"
}High-stakes exams may further analyze answer-time distributions, anomaly clustering, and inter-candidate answer similarity. However, similarity, speed, or camera glitches alone never prove cheating; risk scores merely flag records for human review.
9. Deployment Architecture for 5000 Concurrent Examinees
Traffic pattern: pre-exam login surge, exam-start paper load, sustained answer saves + heartbeats, pre-end submit surge. Separate real-time state, high-frequency behavior data, and core exam data.
Candidate Web/App
|
API Gateway
|
Spring Boot Cluster
|
+---------------+---------------+
| | |
Exam Session Answer Save Proctoring
Service Service Service
| | |
Identity Version Behavior
Verification Control Events
Device Check Auto-save Risk Analysis
Exam Timer Submit Control WebSocket
|
+---------------+---------------+
|
MySQL / Redis / MQ
|
Async Grading / Risk Reports
|
Proctoring Admin DashboardMySQL stores exam records, paper snapshots, answers, submit results, and long-term anomalies. Redis handles heartbeats, session indexes, online status, and timeout acceleration. Message queues drive grading, risk analysis, and cross-instance proctoring notifications. Video proctoring (if required) uses WebRTC with a dedicated media server; Java handles auth, session management, and business events, not raw video frames.
Throughput estimate: 5000 candidates, heartbeat every 15s + answer save every 10s ≈ 833 req/s average. This is a theoretical average; peaks at start/end, DB lock contention, video bandwidth, retries, and request bursts require dedicated load testing, especially the final minute where saves and submits coincide. Monitor: answer save success rate, ack latency, heartbeat timeout rate, auto-submit backlog, grading queue backlog, session anomaly rate.
Privacy: exams collect biometric, camera, and behavioral data. Inform candidates of scope and purpose, follow applicable privacy laws, enforce access controls and retention limits. Routine corporate training need not enable continuous video; proctoring intensity should match exam risk level.
Conclusion
An online exam anti-cheating system involves face recognition, liveness, WebSocket, Redis, random paper generation, device verification, and behavior analysis. But production readiness depends not on the number of detection techniques, but on end-to-end reliability: saved answers survive disconnects; old sessions cannot modify answers after a device switch; the server enforces time limits and auto-submits; anomaly detection avoids false accusations.
For Java developers, the value lies in integrating authentication, state machines, concurrency control, real-time communication, persistence, and rule engines into a complete business scenario. Applicable to academic exams, recruitment, employee training, skill assessment, and online certification. Browser-based proctoring cannot eliminate all cheating; high-security exams need controlled environments, human proctors, and additional verified measures. A mature system reduces cheating risk while ensuring every honest candidate's effort is preserved despite network, device, or algorithmic faults.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.