Introducing Technology to Prevent the Loss of Online Exam Answers

Introducing Technology to Prevent the Loss of Online Exam Answers

While operating an online education site, we began holding regular online exams to assess students’ learning achievements. The exams we prepared were expected to have around 100 simultaneous test-takers. Viewed in terms of the usual web traffic, which is mostly simple page views, this may not seem like a particularly large scale.

However, as we closely examined the characteristics of online exams, we identified one critical risk: at the exact moment the exam ended, all students’ answer-saving and submission requests could arrive simultaneously within a brief one-second window. If this coincided with client retries caused by unstable personal network conditions and automatic submission requests from frontend timers, there was a risk that even a single student’s answers could be lost.

If answers are lost during an actual exam, not only are students’ legitimate efforts undermined, but the trustworthiness of the entire education platform also takes a serious hit. So, before opening the exam to students, our team defined potential answer-loss scenarios and proactively introduced three key technologies to prevent them reliably. In this post, we share which technologies we chose and implemented to address the request surge and concurrency issues at exam end, and how we handled the exam reliably without losing any answers.

1. Answer-Loss Scenarios Identified During Preliminary Checks

Before introducing the technologies, we reviewed the problems that could arise just before an exam ends in a typical synchronous database storage architecture. As a result, we identified three specific ways answers could be lost that could realistically occur during an actual exam.

1.1 Request Surge at Exam End and Packet Reordering

Students typically spend the moments before an exam ends refining written answers or changing multiple-choice selections. If around 100 students all edit their answers in the final few seconds and autosave runs, a large number of write requests can suddenly flood the database. For students using unstable networks such as Wi-Fi or mobile hotspots, packet reordering can occur, where a later request containing the latest edits reaches the server before an earlier one. In a simple overwrite-based architecture, an older request that arrives late can overwrite the latest answers, causing a lost update.

1.2 Race Between Manual Submission and Automatic Timer Submission

One scenario is when a student clicks the Submit button one second before the exam ends at the same time as the browser timer expires and calls the automatic submission API. If client retries due to network latency also occur, multiple submission and save transactions can access the same exam attempt data simultaneously, just milliseconds apart. Without strict state management, a delayed save request could modify finalized answers immediately after automatic submission completes, or a duplicate submission error could occur, putting normal exam closure at risk.

1.3 Client Clock Drift and Deadline Evaluation

The frontend timer follows the system clock on the student’s PC. If the student’s device clock is slower than the server’s, or a packet sent just before the deadline reaches the server one second late due to network latency, the request will have arrived after the deadline according to the server. If the server simply rejects it, the student may lose their final answers despite having submitted on time.

2. Key Technologies Introduced to Prevent Answer Loss and Why We Chose Them

To fundamentally prevent the problems identified above, we introduced three technologies: a Kafka-based autosave pipeline to absorb traffic and manage versions; a submission state machine and retryable submission API to prevent concurrency conflicts; and server-based deadline validation to ensure fairness in determining when submissions are received.

2.1 Kafka-Based Asynchronous Autosave and Version-Based Updates

  • Technology introduced: Apache Kafka event streaming and conditional database updates using client sequence numbers

  • Why we chose it: If the database synchronously handles the many autosave requests generated during an exam and the surge of write traffic just before it ends, connection delays and lock contention are inevitable. So we introduced Kafka to rapidly accept the burst of save requests without losing any and safely apply them at a pace the database can handle.

We also implemented version-based updates to prevent older data from overwriting newer data, even when processing asynchronously through Kafka or when network packets arrive out of order. When sending answers, the client also sends a monotonically increasing sequence number (clientSeq), and we set the Kafka partition key to the attempt session ID (attemptId) to ensure event ordering for each student. Furthermore, when applying updates to the database, we configured conditional update queries so that only requests with a sequence number greater than the currently stored sequence number are applied.

package com.edu.exam.producer;

import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import java.time.Instant;

@Service
public class AnswerAutoSaveProducer {

    private static final String TOPIC_NAME = "exam-answer-autosave-events";
    private final KafkaTemplate<String, AnswerSaveEvent> kafkaTemplate;

    public AnswerAutoSaveProducer(KafkaTemplate<String, AnswerSaveEvent> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    /**
     * Publishes auto-save requests to Kafka partitioned by attemptId
     * to guarantee ordering per examinee and absorb traffic spikes.
     */
    public void publishAutoSaveEvent(long attemptId, long questionId, String content, long clientSeq) {
        AnswerSaveEvent event = new AnswerSaveEvent(
                attemptId,
                questionId,
                content,
                clientSeq,
                Instant.now().toEpochMilli()
        );

        // Using attemptId as the partition key ensures sequential processing for the same user
        kafkaTemplate.send(TOPIC_NAME, String.valueOf(attemptId), event);
    }

    public record AnswerSaveEvent(
            long attemptId,
            long questionId,
            String answerContent,
            long clientSeq,
            long serverReceivedAtMs
    ) {}
}

Kafka consumers read events from the topic and apply them to the database. Even if older packets have already arrived out of order at the network level, the conditional query below safely ignores them without raising an error.

package com.edu.exam.consumer;

import com.edu.exam.producer.AnswerAutoSaveProducer.AnswerSaveEvent;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.Instant;

@Component
public class AnswerAutoSaveConsumer {

    private final NamedParameterJdbcTemplate jdbcTemplate;

    public AnswerAutoSaveConsumer(NamedParameterJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * Consumes auto-save events and performs a version-checked upsert.
     * Prevents out-of-order network packets from overwriting newer answers.
     */
    @KafkaListener(topics = "exam-answer-autosave-events", groupId = "exam-autosave-group")
    public void consumeAndSaveAnswer(AnswerSaveEvent event) {
        String sql = """
            INSERT INTO exam_answer
                (attempt_id, question_id, answer_text, last_client_seq, updated_at)
            VALUES
                (:attemptId, :questionId, :answerText, :clientSeq, :updatedAt)
            ON DUPLICATE KEY UPDATE
                answer_text     = IF(:clientSeq > last_client_seq, :answerText, answer_text),
                updated_at      = IF(:clientSeq > last_client_seq, :updatedAt, updated_at),
                last_client_seq = IF(:clientSeq > last_client_seq, :clientSeq, last_client_seq)
            """;

        MapSqlParameterSource params = new MapSqlParameterSource()
                .addValue("attemptId", event.attemptId())
                .addValue("questionId", event.questionId())
                .addValue("answerText", event.answerContent())
                .addValue("clientSeq", event.clientSeq())
                .addValue("updatedAt", Timestamp.from(Instant.ofEpochMilli(event.serverReceivedAtMs())));

        jdbcTemplate.update(sql, params);
    }
}

With this architecture, even if save requests surge all at once just before the exam ends, the API server can quickly publish events to Kafka and return a response, eliminating the bottleneck. In addition, because the condition :clientSeq > last_client_seq is checked at the database level, the student’s most recently written answers are preserved correctly even if packets arrive out of order.

2.2 Server-Based Deadline Validation (Server Time Authority & Grace Period)

  • Technology introduced: A single server-time authority and validation with a grace period that accounts for network latency

  • Why we chose it: Because a client’s system clock can be inaccurate or manipulated at any time, the server must be the authority for determining whether the deadline has passed. However, mechanically applying server time alone can cause a request sent normally just before the exam ends to be rejected by a narrow margin due to network transmission time. Therefore, we record the arrival time of every request using the server clock, but allow a grace period of several seconds after the official end time to prevent losses caused by network latencyin our design.

We also send the server’s current time to the client when the exam begins, calibrating the on-screen timer so it runs according to the same time reference as the server.

package com.edu.exam.service;

import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.Instant;

@Component
public class ExamTimeValidator {

    // Allow a 3-second grace period to absorb network latency at the exact moment of exam termination
    private static final Duration NETWORK_GRACE_PERIOD = Duration.ofSeconds(3);

    /**
     * Validates whether the incoming request arrived within the authoritative server deadline
     * including the allowed network grace period.
     */
    public boolean isWithinValidSubmissionWindow(Instant officialEndTime, Instant serverArrivedAt) {
        Instant validCutoffTime = officialEndTime.plus(NETWORK_GRACE_PERIOD);
        return !serverArrivedAt.isAfter(validCutoffTime);
    }
}

This validator safely accounts for the physical time it takes for answers written right up to the last moment before the exam ends to travel across the network and reach the server, preventing legitimate answers from being discarded.

2.3 Submission State Machine and Retryable Idempotent Submission API

  • Technology introduced: A unidirectional submission state machine (State Machine) and a state-convergent idempotent (Idempotency) submission API

  • Why we chose it: At the moment an exam ends, a student’s manual submission click, the timer’s automatic submission request, and client retries caused by network timeouts can all happen at once. If the server returns an error simply because it received a duplicate request, the student will see a submission failure message, causing considerable confusion. Also, answers written in the last 1–2 seconds before clicking the Submit button may be lost if they have not yet been autosaved.

To address this, we defined the exam state as a unidirectional state machine that can only transition from IN_PROGRESS -> SUBMITTING -> SUBMITTED (or AUTO_SUBMITTED), and implemented two safeguards.

  1. Atomic state transition (CAS) and idempotent responses: Using a conditional database update (WHERE status = 'IN_PROGRESS'), we ensure that only one of a concurrent manual submission and automatic submission can obtain permission to change the state. Later duplicate or retry requests check that the exam is already closed (SUBMITTED or AUTO_SUBMITTED) and return the same successful submission response instead of an error. This gives us an API that can be safely retried at any time.

  2. Send the final answers along with the submission (Piggybacking): We implemented the submission API so that it includes the latest answer changes in the request body. This allows the final answers to be applied immediately within the submission transaction and the exam state to be closed, regardless of Kafka consumer delays.

package com.edu.exam.service;

import com.edu.exam.consumer.AnswerAutoSaveConsumer;
import com.edu.exam.producer.AnswerAutoSaveProducer.AnswerSaveEvent;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;

@Service
public class ExamSubmissionService {

    private final NamedParameterJdbcTemplate jdbcTemplate;
    private final ExamTimeValidator timeValidator;
    private final AnswerAutoSaveConsumer answerSaver;

    public ExamSubmissionService(
            NamedParameterJdbcTemplate jdbcTemplate,
            ExamTimeValidator timeValidator,
            AnswerAutoSaveConsumer answerSaver) {
        this.jdbcTemplate = jdbcTemplate;
        this.timeValidator = timeValidator;
        this.answerSaver = answerSaver;
    }

    /**
     * Processes final exam submission using a unidirectional state machine.
     * Guarantees idempotency when manual submit, auto submit, and client retries overlap.
     */
    @Transactional
    public SubmissionResult submitExam(long attemptId, boolean isAutoSubmit, List<AnswerSaveEvent> finalAnswers) {
        Instant serverNow = Instant.now();

        ExamAttemptRecord attempt = findAttemptById(attemptId);

        // 1. Idempotency check: If already finalized by a prior request, return success immediately
        if ("SUBMITTED".equals(attempt.status()) || "AUTO_SUBMITTED".equals(attempt.status())) {
            return new SubmissionResult(attemptId, attempt.status(), "ALREADY_COMPLETED_SUCCESS");
        }

        // 2. Atomic State Machine Transition: IN_PROGRESS -> SUBMITTING
        String casSql = """
            UPDATE exam_attempt
            SET status = 'SUBMITTING', updated_at = :now
            WHERE attempt_id = :attemptId AND status = 'IN_PROGRESS'
            """;

        int updatedRows = jdbcTemplate.update(casSql, new MapSqlParameterSource()
                .addValue("attemptId", attemptId)
                .addValue("now", Timestamp.from(serverNow)));
        if (updatedRows == 0) {
            // Another concurrent request is already processing or has just finished submission
            ExamAttemptRecord refreshed = findAttemptById(attemptId);
            if ("SUBMITTED".equals(refreshed.status()) || "AUTO_SUBMITTED".equals(refreshed.status())) {
                return new SubmissionResult(attemptId, refreshed.status(), "CONVERGED_SUCCESS");
            }
            throw new IllegalStateException("Submission is currently in progress. Please retry.");
        }

        // 3. Validate server deadline and flush final piggybacked answers using version check
        if (timeValidator.isWithinValidSubmissionWindow(attempt.officialEndTime(), serverNow) && finalAnswers != null) {
            for (AnswerSaveEvent answer : finalAnswers) {
                answerSaver.consumeAndSaveAnswer(new AnswerSaveEvent(
                        attemptId,
                        answer.questionId(),
                        answer.answerContent(),
                        answer.clientSeq(),
                        serverNow.toEpochMilli()
                ));
            }
        }

        // 4. Finalize state transition: SUBMITTING -> SUBMITTED or AUTO_SUBMITTED
        String targetStatus = isAutoSubmit ? "AUTO_SUBMITTED" : "SUBMITTED";
        String finalizeSql = """
            UPDATE exam_attempt
            SET status = :targetStatus, submitted_at = :now, updated_at = :now
            WHERE attempt_id = :attemptId AND status = 'SUBMITTING'
            """;

        jdbcTemplate.update(finalizeSql, new MapSqlParameterSource()
                .addValue("attemptId", attemptId)
                .addValue("targetStatus", targetStatus)
                .addValue("now", Timestamp.from(serverNow)));

        return new SubmissionResult(attemptId, targetStatus, "NEWLY_SUBMITTED_SUCCESS");
    }

    private ExamAttemptRecord findAttemptById(long attemptId) {
        String sql = "SELECT attempt_id, status, official_end_time FROM exam_attempt WHERE attempt_id = :id";
        return jdbcTemplate.queryForObject(sql, new MapSqlParameterSource("id", attemptId), (rs, rowNum) ->
                new ExamAttemptRecord(
                        rs.getLong("attempt_id"),
                        rs.getString("status"),
                        rs.getTimestamp("official_end_time").toInstant()
                )
        );
    }

    public record ExamAttemptRecord(long attemptId, String status, Instant officialEndTime) {}
    public record SubmissionResult(long attemptId, String finalStatus, String resultCode) {}
}

With this design, once a submission is complete, even if delayed autosave events remain in the Kafka queue and are processed later by a consumer, the final answer with the highest sequence number has already been applied to the database at the time of submission, keeping the data safe. We also added a safeguard for students who cannot send a submission request at all, for example because their PC loses power: a server scheduler periodically finds IN_PROGRESS sessions whose deadlines have passed and safely closes them automatically using the same state machine logic.

3. Results and Conclusion

Before holding an actual exam, we applied the three key technologies described above to the system, tested them, and then ran an online exam for around 100 students.

During the exam and at the exact moment it ended, students’ answer-editing and submission requests arrived all at once. Thanks to the Kafka-based asynchronous autosave pipeline, the server and database handled every request reliably without any bottlenecks or delays. Some students with unstable network conditions experienced packet reordering, but sequence-number-based conditional updates correctly filtered out older data and preserved the most recently written answers intact.

In particular, the unidirectional submission state machine and idempotent API worked as intended even when students clicked the manual submission button while the timer’s automatic submission was triggered, or when a temporary network disconnection led to retries. Every student’s submission process converged smoothly without displaying errors caused by duplicate requests. Server-based deadline and grace period validation also ensured that even the final answers sent just before the exam ended were all included in grading, without a single answer being lost.

Although this was not a massive exam with tens of thousands of simultaneous users, the technical challenges unique to online exams—traffic concentrating at the end and multiple requests competing with one another—are the same regardless of scale. Rather than responding after problems occurred, we identified potential loss scenarios in advance and proactively introduced Kafka-based version-controlled autosave, server-time-based validation, and a retryable submission API based on a state machine. This enabled us to provide students with a reliable and stable exam environment.

dwmoon

Site footer