Securely Recording Personal Information Access Logs

Securely Recording Personal Information Access Logs

While developing the BanJangNote backend, I worked across several domains, but I gave a lot of thought to the personal information audit logging system.

At first, I was so busy building core business features like recruiting and job seeking that I barely had time to think about anything else. But as feature development for the service began to wrap up, it was time to put a proper audit logging system in place to comply with the Personal Information Protection Act—a task I had been putting off. In particular, BanJangNote is a platform where large amounts of personal information are exchanged during the hiring process, so simply writing a few lines to log files was not going to cut it.

Once I actually started, I realized that the legal requirements were strict, and with more than 300 APIs, relying on people to remember where to add logs one by one was bound to lead to omissions as the system continued to evolve. So I’d like to share how I built a pipeline to prevent audit log omissions while maintaining API response times under high traffic.

Turning legal provisions into code specifications

Article 29 of the Personal Information Protection Act requires organizations to retain records of system access and take safety measures to prevent those records from being altered or falsified. More detailed requirements can be found in Article 8 of the Notice on Standards for Ensuring the Safety of Personal Information.

Here’s a summary of what the law requires us to record in personal information access logs.

First, there are five required items that must always be included in an access log.

  • An identifier (ID or account) that shows who accessed the system

  • The date and time of access

  • The IP address from which the system was accessed

  • The task performed, showing what action was taken in the system, such as viewing, modifying, deleting, or downloading

  • And an identifier for the data subject whose information was accessed

There are also a few additional requirements.

  • Records must be retained for at least two years when handling information about 50,000 or more people or unique identifying information.

  • Once a record has been stored, no one should be able to alter it arbitrarily.

  • When downloading personal information as an Excel spreadsheet or other file, the reason for the download must be recorded.

  • It must be possible to monitor regularly for bulk queries or unusual access patterns.

The requirements themselves were clear, but when I considered how to implement them in code, I saw a few obstacles.

Challenges I ran into while building it

In a Spring environment, interceptors and AOP are usually the first things that come to mind for audit logging. Early in the design process, I considered intercepting requests at the front end with an interceptor and recording them. But when I started working through the design, it turned out not to be that simple.

1. There are hundreds of endpoints. Can anyone really keep track of them all?

BanJangNote had more than 300 APIs, split by role—for foremen, team leaders, administrators, and so on. It’s not realistic to expect developers to remember every time they create a new API that “this handles personal information, so I need to log it.” When you’re busy developing, it’s easy to miss something, and code reviews alone have clear limitations when it comes to catching these omissions. The reverse problem also came up: when an existing API was deleted or its path changed, its old configuration could be left behind.

2. An interceptor doesn’t know whose information was accessed

An interceptor can easily identify the URL and request headers sent by the client, as well as the token of the logged-in user. But it has no way to determine the “data subject identifier” required by law—in other words, “whose personal information did this person view?” For example, if an API retrieves a list of foremen at a particular worksite, the member IDs of the 10 workers in the results are only known after the service logic queries the database. In effect, the data was being lost between the web layer’s interceptor and the business logic layer.

3. Can the database handle an INSERT every time someone views data?

Given the nature of construction sites, we expected queries to spike during the early-morning arrival period. If we ran a synchronous INSERT into the audit log table every time a list containing personal information was requested, it seemed likely to put immediate strain on the DB connection pool. The result could be that the critical business APIs became slower just because we were recording audit logs. We also needed to avoid rolling back users’ actual tasks—such as viewing job listings or checking their work hours—just because a temporary DB lock or delay occurred while writing an audit log.

4. Secondary leaks caused by the logs themselves

If we serialize entire response objects and dump them into the log table in the name of thorough audit logging, the table itself becomes a dangerous repository of plain-text resident registration numbers and bank account numbers. We needed to hide the data itself and record only metadata indicating the kinds of fields accessed, such as names, phone numbers, or account details.

Solving the problems

1. Preventing missing audit records: requiring every endpoint to be registered through test code

I decided that the only way to avoid relying on people’s memory was to make the build itself fail whenever an endpoint was left unregistered.

First, I created a registry class and required every endpoint in the system to be registered, either as handling personal information or as not handling it. Even endpoints that didn’t handle personal information couldn’t simply be left unclassified: they had to be registered with a reason code, such as whether they were for health checks or simply for updating a user’s own information.

// 대상 엔드포인트 등록
AccessLogTargetRegistry.register(
    "/feature/cm/find-somebodys-detail/fetch",
    true,
    AccessTaskType.Read,
    List.of(
        PersonalDataItem.Name,
        PersonalDataItem.Phone,
        PersonalDataItem.BirthDate,
        PersonalDataItem.Certificate
    )
);

// 비대상 엔드포인트도 사유와 함께 명시
AccessLogNonTargetDeclarations.registerNonTarget(
    "/actuator/health", 
    NonTargetReason.HealthCheck
);

Then, using Spring’s metadata reader, I wrote a test that collects the URL paths of every @RestController in the project.

class AccessLogTargetRegistryArchitectureTest {

    @Test
    @DisplayName("모든 Resource 엔드포인트가 레지스트리에 등록되어 있어야 한다")
    void allRoleResourceEndpointsMustBeRegistered() throws Exception {
        Set<String> discoveredEndpoints = scanAllRoleResourceEndpoints();

        // 레지스트리에 대상이든 비대상이든 등록되지 않은 엔드포인트를 찾는다
        List<String> missing = discoveredEndpoints.stream()
                .filter(ep -> !AccessLogTargetRegistry.contains(ep))
                .toList();

        // 하나라도 빠져 있으면 테스트 실패
        assertTrue(missing.isEmpty(),
                "AccessLogTargetRegistry에 등록되지 않은 엔드포인트가 있습니다: " + missing);
    }

    @Test
    @DisplayName("코드에서 삭제된 엔드포인트가 레지스트리에 남아있으면 안 된다")
    void registryMustNotContainStaleEndpoints() throws Exception {
        Set<String> realEndpoints = scanAllRoleResourceEndpoints();
        List<String> stale = AccessLogTargetRegistry.getAll().keySet().stream()
                .filter(ep -> !realEndpoints.contains(ep))
                .sorted()
                .toList();
        assertTrue(stale.isEmpty(), "실제 코드에 없는 엔드포인트가 레지스트리에 남아있습니다: " + stale);
    }
}

With this in place, if a developer created a new API but didn’t register it, the regression tests and CI process would catch the missing API audit record. They would also catch deleted APIs left in the registry. This kept endpoint registrations 100% up to date without requiring developers to pay separate attention to them.

2. Passing business context through ThreadLocal

I bridged the gap between the interceptor and the business logic by creating a ThreadLocal-based context (AccessLogContext).

When a request comes in, the interceptor sets information such as the caller, client IP, and request time in AccessLogContext during preHandle.

Later, after the request passes through the controller and reaches the service logic, the service retrieves the actual data from the DB and calls a method to record the data subject and the personal information being accessed in the context.

@Service
@Transactional
public class WorkLdrFlow {
    //
    public WorkCrewMemberDetailRdo findMemberDetail(FindWorkCrewMemberDetailUdo udo) {
        //
        // 조회 대상이 된 정보주체 식별자를 컨텍스트(AccessLogContext)에 전달
        AccessLogContext.reportTargetSubject(udo.getMemberId(), AccessLogSubjectKind.Member);

        // 실제 업무 로직 수행
        return workCrewTask.findMemberDetail(udo.getMemberId());
    }
}

This lets the business logic record information in the context by adding just one line, keeping complex logging logic from intruding into the service layer.

Then, when the request finishes, afterCompletion in the interceptor combines this information to create the final log object.

3. Maintaining response speed with asynchronous batching

To maintain the response times of business APIs, the interceptor doesn’t send queries directly to the DB. Instead, it places objects in an in-memory buffer (AccessLogBatchAccumulator) and returns immediately.

@Component("accessLogBatchAccumulator")
@RequiredArgsConstructor
public class AccessLogBatchAccumulator {

    private final AccessLogBulkInsertStore bulkInsertStore;
    private final List<AccessLogCdo> buffer = new ArrayList<>();
    private final Object bufferLock = new Object();

    private int batchSize = 200; // 200건 기준
    private long flushIntervalMs = 1000; // 1초 주기
    private volatile long lastFlushTime = System.currentTimeMillis();

    public void add(AccessLogCdo cdo) {
        if (cdo == null) return;
        boolean shouldFlush = false;

        // 버퍼에 담을 때만 빠르게 락을 잡고 빠진다
        synchronized (bufferLock) {
            buffer.add(cdo);
            if (buffer.size() >= batchSize) {
                shouldFlush = true;
            }
        }

        // 실제 무거운 DB 작업은 락 바깥에서 수행
        if (shouldFlush) {
            drainAndInsert();
        }
    }

    @Scheduled(fixedDelayString = "1000")
    public void scheduledFlush() {
        // 200건이 안 차더라도 1초가 지나면 남아있는 로그를 비워준다
        boolean hasItems;
        long elapsed;
        synchronized (bufferLock) {
            hasItems = !buffer.isEmpty();
            elapsed = System.currentTimeMillis() - lastFlushTime;
        }
        if (hasItems && elapsed >= flushIntervalMs) {
            drainAndInsert();
        }
    }

    private void drainAndInsert() {
        List<AccessLogCdo> toInsert;
        synchronized (bufferLock) {
            if (buffer.isEmpty()) return;
            toInsert = new ArrayList<>(buffer);
            buffer.clear();
            lastFlushTime = System.currentTimeMillis();
        }

        // 별도 트랜잭션으로 JDBC Batch Insert 실행
        bulkInsertStore.insertAllInNewTransaction(toInsert);
    }

    @PreDestroy
    public void onShutdown() {
        // 서버가 내려갈 때 버퍼에 남은 로그를 비우고 종료
        drainAndInsert();
    }
}

The in-memory buffer also uses native batchUpdate instead of JPA saveAll, grouping records into batches of 200 for insertion to minimize the load on the DB and network.

At the same time, it acquires a short-lived lock only when adding records to the buffer, while keeping the heavy DB I/O outside the lock. This prevents bottlenecks caused by threads waiting on one another. To avoid losing logs waiting in memory when the server is redeployed or shut down, @PreDestroy saves all remaining data before the server exits.

Personal information audit logs are the service’s black box

When you’re developing a service, security and legal compliance work can easily get pushed back. It’s not a feature users can see right away, and there are so many rules to keep track of that, honestly, it can often feel like a tedious chore.

But the data we handle isn’t just text stored in a database. It represents someone in the online world; it’s a label that can identify a real person living in the real world. If this information is managed carelessly and leaks, users are the ones who bear the consequences. Users trust our service with their personal information, and I realized it’s a developer’s responsibility to honor that trust through the systems we build.

Audit logs are also a safeguard not only for users, but for our service and developers themselves. If there’s suspicious external access or a suspected data breach, developers have no way to defend themselves without clear records of who accessed what data, when, and from where. With carefully maintained access logs, we can clearly explain that “our system followed the proper procedures, and this is the extent of the affected account’s access.”

I see compliance and safety measures not as things that slow down service development, but as preparation to prevent accidents when we’re moving at a much faster pace later on. With a reliable black box in place, we’ll be able to develop new features with confidence as the service continues to grow and evolve.

informalife

Site footer