Spring › Feature

Immutable raw data storage and local reparsing in Spring Boot

Store immutable external API JSON responses in PostgreSQL and reparse tens of thousands of records locally with zero API quota usage when parser rules change.

Immutable raw data storage and local reparsing in Spring Boot

Mapping external API responses straight into domain entities feels fast at first, until a parser bug or a new field forces you to re-fetch tens of thousands of records against a strict daily quota. In this post, I show how storing immutable raw JSON in PostgreSQL alongside a versioned parser lets you reparse an entire dataset locally in under two minutes with zero upstream API calls.

Built with Spring Boot, Kotlin, Spring Data JPA, Jackson, and PostgreSQL.


Why mapping API responses directly to domain entities hurts later

When teams integrate a public Open API, payment gateway, or weather feed, the default pipeline usually looks like this:

1
[External API Call] -> [Jackson DTO Deserialization] -> [Domain Entity] -> [RDBMS Save]

That works fine during initial prototyping, but in a production ingestion pipeline it breaks down in three predictable ways:

  1. Parser bugs trigger expensive full re-fetches: While running my court-ruling collector (demo-backend-server), I discovered an edge-case bug in the regex that extracts presiding and rapporteur justices from the signature block at the end of each ruling. Without the raw responses stored locally, fixing that parser meant re-calling a public API capped at 1 request/second and 10,000 requests/day for several days.
  2. New business fields can’t backfill historical records: Early on, we only stored the case number, title, and verdict summary. Later we needed cited statutes, cited precedents, and historical Dangi-to-Gregorian calendar conversion (Korean court rulings prior to 1961 used the Dangi era, offset by 2,333 years). Without raw payloads, tens of thousands of existing rows stay permanently incomplete.
  3. No forensic evidence for malformed upstream payloads: Public APIs occasionally return an HTML error notice or a JSON stub ({"Law":"No matching precedent found."}) instead of the expected structure. If the pipeline discards the raw body on failure, you have no way to inspect or write a regression test for what actually arrived.
flowchart TD
    A1["External API Call"] --> B1["Immediate Parse & DTO Mapping"]
    B1 --> C1["Save Domain Entity"]
    B1 -. "Parser bug or new field" .-> D1["Full API re-fetch required (quota exhaustion & rate limits)"]

To break that coupling, I split ingestion and transformation into two independent stages backed by an immutable raw table.


Two-stage architecture: immutable raw table + local reparsing

The redesigned pipeline separates collecting bytes from interpreting them:

flowchart TD
    subgraph Phase1["Stage 1: Collection & Immutable Storage"]
        API["External Open API"] --> Client["LawPrecedentClient"]
        Client -->|"Raw JSON"| Import["JudgmentImportService.collect()"]
        Import -->|"UPSERT raw payload"| RawDB[("raw_judgments\n(immutable rawJson)")]
        RawDB -->|"Initial parse"| Parser["JudgmentParser\n(version: law-prec-v4)"]
        Parser -->|"Success"| MainDB[("judgments\n(domain table)")]
        Parser -.->|"Failure"| Pending["Record raw.parseError\n(keep raw payload)"]
    end
    subgraph Phase2["Stage 2: Zero-Quota Local Reparse"]
        Batch["judgment-reparse Batch"] -->|"0 external calls"| RawDB
        RawDB -->|"Re-parse with latest version"| Parser
        Parser -->|"Idempotent update"| MainDB
    end

Three rules govern this pipeline:

  • Persist raw JSON first, always: Every response payload (rawJson) is written to raw_judgments regardless of whether parsing succeeds or fails.
  • Track parser version and status on the raw row: Each row records parserVersion, parsedAt, and parseError so the system knows exactly which records are stale or failed.
  • Reparse strictly from local PostgreSQL: When you bump JudgmentParser.VERSION or fix a bug, a background batch re-processes outdated rows in memory without touching the external API.

Admin raw JSON viewer showing an immutable API payload Figure 1. The admin raw JSON viewer (/admin/raw-judgments/{id}). Preserving the exact upstream response makes every record replayable whenever parsing rules evolve.


Entity design: separating RawJudgment and Judgment

1. Immutable raw entity (RawJudgment)

RawJudgment stores the exact upstream JSON payload plus list-level metadata used for cross-validation. It is never exposed through public APIs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// src/main/kotlin/com/example/server/judgment/domain/RawJudgment.kt
package com.example.server.judgment.domain

import com.example.server.common.BaseEntity
import jakarta.persistence.*
import org.hibernate.Length
import java.time.Instant

/**
 * Latest raw payload from the official Open API.
 * Never exposed to public endpoints; serves as the permanent input for local reparsing.
 */
@Entity
@Table(name = "raw_judgments")
class RawJudgment(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,

    @Column(nullable = false, unique = true)
    val precSerial: Long,

    @Column(nullable = false, length = Length.LONG32)
    var rawJson: String,

    @Column(nullable = false)
    var collectedAt: Instant = Instant.now(),

    var parserVersion: String? = null,
    var parsedAt: Instant? = null,

    @Column(length = Length.LONG32)
    var parseError: String? = null,

    /** List-endpoint metadata stored for cross-checking against the detail payload */
    @Column(length = 100)
    var dataSourceName: String? = null,

    var listCaseNumber: String? = null,
    var listCourtName: String? = null,

    @Column(length = 20)
    var listSentenceDate: String? = null,
) : BaseEntity()

Using Hibernate’s Length.LONG32 maps rawJson to PostgreSQL’s TEXT type, which holds multi-hundred-kilobyte full court rulings without truncation.

2. Domain entity (Judgment) with parser lineage

The serving domain table also records parserVersion, parsedAt, and judgeReviewNotes so operators can audit which parser version produced the current row.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// src/main/kotlin/com/example/server/judgment/domain/Judgment.kt
@Entity
@Table(name = "judgments")
class Judgment(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,

    @Column(nullable = false, unique = true)
    var precSerial: Long? = null,

    @Column(nullable = false)
    var caseNumber: String,

    @Column(nullable = false, length = Length.LONG32)
    var verdict: String,

    // ... other domain fields (courtName, sentenceDate, fullText, judges, etc.) ...

    var parserVersion: String? = null,
    var parsedAt: Instant? = null,
    var judgeReviewNotes: String? = null,
) : BaseEntity()

Versioned parser implementation (JudgmentParser)

JudgmentParser declares an explicit VERSION constant (law-prec-v4). Any change to normalization rules, date conversion, or judge-signature extraction bumps this constant, automatically marking older rows as reparse candidates.

(Note: The upstream Korean legal API returns Korean JSON field keys and Korean judicial titles; field keys and patterns below are localized to English for readability while preserving the exact parsing logic.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// src/main/kotlin/com/example/server/judgment/application/JudgmentParser.kt
package com.example.server.judgment.application

import com.example.server.judgment.domain.JudgeRole
import org.springframework.stereotype.Component
import tools.jackson.databind.JsonNode
import tools.jackson.databind.json.JsonMapper
import java.time.LocalDate
import java.time.format.DateTimeFormatter

data class ParsedJudge(val name: String, val role: JudgeRole, val rapporteur: Boolean)

data class ParsedJudgment(
    val precSerial: Long,
    val caseNumber: String,
    val caseName: String?,
    val courtName: String?,
    val sentenceDate: LocalDate?,
    val caseType: String?,
    val judgmentType: String?,
    val verdict: String,
    val issues: String?,
    val referenceProvisions: String?,
    val referenceJudgments: String?,
    val fullText: String?,
    val judges: List<ParsedJudge>,
    val judgeReviewNotes: String?,
)

@Component
class JudgmentParser(private val mapper: JsonMapper) {

    fun parse(precSerial: Long, rawJson: String): ParsedJudgment {
        val root = try {
            mapper.readTree(rawJson)
        } catch (e: Exception) {
            throw JudgmentParseException("Raw payload is not valid JSON.")
        }

        // Guard against HTML-only or unavailable text notices
        if (root?.path("PrecService")?.isMissingNode == true && root.path("Law").isString) {
            throw JudgmentParseException(UNAVAILABLE)
        }

        val node = root?.path("PrecService") ?: throw JudgmentParseException("Missing PrecService payload.")
        if (!node.isObject || value(node, "precSerialNo")?.toLongOrNull() != precSerial || precSerial <= 0) {
            throw JudgmentParseException("Raw payload serial number does not match expected ID.")
        }

        val caseNumber = short(node, "caseNumber") ?: throw JudgmentParseException("Missing case number in raw payload.")
        val fullText = value(node, "fullText")
        val (judges, review) = signature(fullText)

        return ParsedJudgment(
            precSerial = precSerial,
            caseNumber = caseNumber,
            caseName = short(node, "caseName"),
            courtName = short(node, "courtName")?.let(::normalizeCourtName),
            sentenceDate = parseDate(value(node, "sentenceDate")),
            caseType = short(node, "caseType"),
            judgmentType = short(node, "judgmentType"),
            verdict = value(node, "verdict").orEmpty(),
            issues = value(node, "issues"),
            referenceProvisions = value(node, "referenceProvisions"),
            referenceJudgments = value(node, "referenceJudgments"),
            fullText = fullText,
            judges = judges,
            judgeReviewNotes = review
        )
    }

    /** Expand abbreviated court names into canonical full names */
    private fun normalizeCourtName(value: String): String = value
        .replace(Regex("\\bHigh Ct\\.?$"), "High Court")
        .replace(Regex("\\bDist\\. Ct\\.?$"), "District Court")

    /** Convert pre-1961 Dangi calendar years and handle unknown-date placeholders */
    private fun parseDate(value: String?): LocalDate? {
        if (value == null) return null
        val digits = value.replace(Regex("[. /\\-\\s]"), "")
        if (!digits.matches(Regex("\\d{8}"))) throw JudgmentParseException("Invalid sentence date format.")
        if (digits == UNKNOWN_DATE) return null // Workers' comp placeholder '00010101'

        val parsed = try {
            LocalDate.parse(digits, DateTimeFormatter.BASIC_ISO_DATE)
        } catch (e: Exception) {
            throw JudgmentParseException("Sentence date is not a valid calendar date.")
        }

        if (parsed.year < DANGI_MIN_YEAR) return parsed
        // Dangi 4288 -> Gregorian 1955 (DANGI_OFFSET = 2333)
        return parsed.minusYears(DANGI_OFFSET).takeIf { it.year <= DANGI_LAST_YEAR }
            ?: throw JudgmentParseException("Sentence date is outside valid Dangi range.")
    }

    /** Extract judge names, roles, and rapporteur flags from the trailing signature block */
    private fun signature(fullText: String?): Pair<List<ParsedJudge>, String?> {
        if (fullText == null) return emptyList<ParsedJudge>() to null
        val lines = fullText.lines().map(String::trim).filter(String::isNotEmpty)
        var start = lines.indexOfLast { PREFIX.containsMatchIn(it) }
        if (start < 0 || start < lines.size - 12) return emptyList<ParsedJudge>() to null
        while (start > 0 && PREFIX.containsMatchIn(lines[start - 1])) start--

        val candidates = mutableListOf<Pair<String, Set<String>>>()
        for (line in lines.drop(start)) {
            val prefix = PREFIX.find(line)
            val content = if (prefix == null) line else line.substring(prefix.range.last + 1)
            val names = NAME.findAll(content).toList()
            var cursor = 0
            if (names.isEmpty()) return unrecognized()
            names.forEachIndexed { index, match ->
                if (!content.substring(cursor, match.range.first).matches(SEPARATOR)) return unrecognized()
                val labels = match.groupValues[2].replace(Regex("\\s+"), "").split(Regex("[,/]"))
                    .filter(String::isNotEmpty).toMutableSet()
                if (index == 0) prefix?.groupValues?.get(1)?.takeIf(String::isNotBlank)?.let(labels::add)
                if (!setOf("Presiding", "Rapporteur", "Sole").containsAll(labels)) return unrecognized()
                candidates.add(match.groupValues[1].trim() to labels)
                cursor = match.range.last + 1
            }
            if (!content.substring(cursor).matches(SEPARATOR)) return unrecognized()
        }

        val hasPresiding = candidates.any { "Presiding" in it.second }
        return candidates.map { (name, labels) ->
            val role = when {
                "Presiding" in labels -> JudgeRole.PRESIDING
                "Sole" in labels -> JudgeRole.SOLE
                hasPresiding -> JudgeRole.ASSOCIATE
                else -> JudgeRole.UNKNOWN
            }
            ParsedJudge(name, role, "Rapporteur" in labels)
        } to (if (candidates.any { !hasPresiding && "Sole" !in it.second && "Presiding" !in it.second })
            "Some judge roles in the signature block could not be determined." else null)
    }

    companion object {
        const val VERSION = "law-prec-v4"
        private const val DANGI_MIN_YEAR = 4000
        private const val DANGI_OFFSET = 2333L
        private const val DANGI_LAST_YEAR = 1961
        const val UNKNOWN_DATE = "00010101"
        const val UNAVAILABLE = "Official API does not provide JSON full text for this record."
        private val PREFIX = Regex("^(?:(Presiding|Rapporteur|Sole)\\s+)?(?:Chief Justice|Justice|Judge)\\s+")
        private val NAME = Regex("([A-Z][a-z]+\\s+[A-Z][a-z]+)(?:\\s*\\(([^()]*)\\))?")
        private val SEPARATOR = Regex("[\\s,;]*")
    }
}

For a deeper look at the real-world parsing edge cases behind normalizeCourtName() and parseDate(), see my public-data parsing troubleshooting notes.


Shared ingestion and reparsing service (JudgmentImportService)

JudgmentImportService exposes two entry points that share the exact same parseAndApply() logic:

  1. collect(): Persists the incoming raw JSON first, then parses and applies it to judgments.
  2. reparse(): Reads the saved RawJudgment directly from PostgreSQL and re-runs parseAndApply() with zero network I/O.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// src/main/kotlin/com/example/server/judgment/application/JudgmentImportService.kt
package com.example.server.judgment.application

import com.example.server.judgment.domain.*
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.Instant

data class JudgmentImportResult(val judgmentId: Long?, val error: String?)

@Service
class JudgmentImportService(
    private val parser: JudgmentParser,
    private val rawRepository: RawJudgmentJpaRepository,
    private val judgmentRepository: JudgmentJpaRepository,
    private val judgeRepository: JudgeJpaRepository,
) {
    /** Stage 1: Called when collecting from the external API */
    @Transactional
    fun collect(
        precSerial: Long,
        rawJson: String,
        collectedAt: Instant = Instant.now(),
        listing: JudgmentListing? = null,
        dataSourceName: String? = null
    ): JudgmentImportResult {
        require(precSerial > 0) { "precSerial must be positive." }

        val raw = rawRepository.findByPrecSerial(precSerial)
            ?: RawJudgment(precSerial = precSerial, rawJson = rawJson, collectedAt = collectedAt)

        raw.rawJson = rawJson
        raw.collectedAt = collectedAt
        raw.parserVersion = null
        raw.parsedAt = null
        raw.parseError = null
        if (dataSourceName != null) raw.dataSourceName = dataSourceName

        raw.listCaseNumber = listing?.caseNumber
        raw.listCourtName = listing?.courtName
        raw.listSentenceDate = listing?.sentenceDate

        rawRepository.save(raw)
        return parseAndApply(raw)
    }

    /** Stage 2: Local-only reparse with zero external API calls */
    @Transactional
    fun reparse(precSerial: Long): JudgmentImportResult {
        val raw = rawRepository.findByPrecSerial(precSerial)
            ?: throw JudgmentParseException("No stored raw record found to reparse.")
        return parseAndApply(raw)
    }

    /** Idempotently parses raw JSON and updates the domain entity */
    private fun parseAndApply(raw: RawJudgment): JudgmentImportResult {
        raw.parserVersion = JudgmentParser.VERSION

        // 1. Run parser and capture domain parse errors without rolling back raw storage
        val parsed = try {
            parser.parse(raw.precSerial, raw.rawJson)
        } catch (e: JudgmentParseException) {
            return reject(raw, e.message!!)
        }

        // 2. Cross-check list metadata against detail payload
        listingMismatch(raw, parsed)?.let { return reject(raw, it) }

        // 3. Protect soft-deleted and manually curated records
        val storedId = judgmentRepository.findIdIncludingDeletedByPrecSerial(raw.precSerial)
        val existing = storedId?.let { judgmentRepository.findByIdOrNull(it) }
        if (storedId != null && existing == null) {
            return reject(raw, "Record is in the trash bin. Restore it before reparsing.")
        }
        if (existing?.source == JudgmentSource.MANUAL) {
            return reject(raw, "Conflicts with a manually curated judgment. Skipping auto-overwrite.")
        }

        // 4. Match judges safely (defer linking if duplicate names exist in the same court)
        val judgment = existing ?: Judgment(caseNumber = parsed.caseNumber, verdict = parsed.verdict)
        val review = mutableListOf<String>()
        parsed.judgeReviewNotes?.let(review::add)

        val matches = if (parsed.courtName == null || parsed.judges.isEmpty()) emptyMap() else
            judgeRepository.findAllByNameInAndCourt(parsed.judges.map { it.name }, parsed.courtName).groupBy { it.name }

        val assignments = parsed.judges.mapNotNull { person ->
            if (parsed.courtName == null) {
                review.add("Unknown court: deferred auto-linking for ${person.name}")
                return@mapNotNull null
            }
            val candidates = matches[person.name].orEmpty()
            val judge = when (candidates.size) {
                0 -> judgeRepository.save(Judge(name = person.name, court = parsed.courtName))
                1 -> candidates.single()
                else -> {
                    review.add("Ambiguous judge name: deferred auto-linking for ${person.name}")
                    return@mapNotNull null
                }
            }
            judge to person.role
        }

        // 5. Apply parsed fields to the domain entity
        judgment.update(parsed.caseNumber, parsed.verdict)
        judgment.precSerial = parsed.precSerial
        judgment.caseName = parsed.caseName
        judgment.courtName = parsed.courtName
        judgment.sentenceDate = parsed.sentenceDate
        judgment.fullText = parsed.fullText
        judgment.parserVersion = JudgmentParser.VERSION
        judgment.parsedAt = Instant.now()
        judgment.judgeReviewNotes = review.distinct().joinToString("\n").ifEmpty { null }
        judgment.replaceJudges(assignments)

        judgmentRepository.save(judgment)

        raw.parsedAt = judgment.parsedAt
        raw.parseError = null
        return JudgmentImportResult(judgment.id, null)
    }

    private fun reject(raw: RawJudgment, error: String): JudgmentImportResult {
        raw.parsedAt = null
        raw.parseError = error
        return JudgmentImportResult(null, error)
    }
}

Notice what reject() does on failure: it doesn’t roll back the transaction and discard the raw payload. It commits raw.parsedAt = null and raw.parseError = error, keeping the original JSON intact so you can inspect it in the admin UI and reparse it after fixing the bug.


Zero-quota local reparse batch and measured speedup

Whenever I deploy a new parser version (law-prec-v4), a scheduled batch job (judgment-reparse) scans outdated or previously failed raw rows in keyset order using the JSON checkpoint resume pattern:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// src/main/kotlin/com/example/server/judgment/application/JudgmentCollectionJobs.kt
@Bean
fun judgmentReparseJob(): JobDefinition = object : JobDefinition {
    override val name = "judgment-reparse"
    override val description = "Reparse outdated or failed raw records locally (0 external calls, 100/run)"
    override val defaultCron = "0 0 5 * * *"
    override fun execute(context: JobContext) = reparse(context)
}

private fun reparse(context: JobContext) {
    var cursor = context.checkpoint?.let { decode(it, JudgmentReparseCursor::class.java) }?.takeUnless { it.done }
        ?: JudgmentReparseCursor(upper = rawRepository.maximumId())

    val candidates = rawRepository.reparseCandidates(
        after = cursor.after,
        upper = cursor.upper,
        currentVersion = JudgmentParser.VERSION,
        pageable = PageRequest.of(0, properties.maxItemsPerRun)
    )

    context.total(candidates.size.toLong())
    for (serial in candidates) {
        context.check()
        val raw = rawRepository.findByPrecSerial(serial) ?: error("Raw record was deleted before reparse.")
        val next = cursor.copy(after = raw.id)

        // Zero external API calls: reads solely from local PostgreSQL
        context.processResult("prec:$serial", mapper.writeValueAsString(next)) {
            importer.reparse(serial).error
        }
        cursor = next
    }

    if (candidates.size < properties.maxItemsPerRun) {
        context.checkpoint(mapper.writeValueAsString(cursor.copy(done = true)))
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/main/kotlin/com/example/server/judgment/domain/RawJudgmentJpaRepository.kt
@Query("""
    SELECT r.precSerial FROM RawJudgment r
    WHERE r.id > :after AND r.id <= :upper
      AND (r.parserVersion IS NULL OR r.parserVersion != :currentVersion OR r.parsedAt IS NULL)
    ORDER BY r.id ASC
""")
fun reparseCandidates(
    after: Long,
    upper: Long,
    currentVersion: String,
    pageable: Pageable
): List<Long>

Terminal output showing local reparse batch running at 110 records per second Figure 2. Local reparse batch console output after a parser version bump. With network RTT removed, PostgreSQL + Jackson reparsing sustains ~110 records/second with zero external API quota used.

Benchmark: external re-fetch vs. local reparse (10,000 records)

MetricExternal API Re-fetchLocal Raw ReparseImprovement
External API calls10,000 (100% of daily quota)0 callsZero quota burn
Time per record~800ms–1,200ms (network RTT)~9.1ms (in-memory Jackson)~88x faster
Total time (10k rows)~2 hours 45 minutes (rate-limited)~1 minute 30 secondsSame-deploy backfill
Failure recoveryRetry over flaky networkSafe checkpoint resumeZero data loss

Protecting domain integrity with four guardrails

Bad upstream rows should neither crash the pipeline nor silently corrupt domain tables. parseAndApply() enforces four guardrails and routes rejected rows to a review queue:

  1. List-vs-detail cross-validation (listingMismatch): Rejects records whose detail case number, court, or sentence date contradicts the list response.
  2. Duplicate judge name safety: If two judges share the same name at the same court, skips auto-linking and records a note in judgeReviewNotes for manual review.
  3. Manual-record protection: Refuses to overwrite records marked JudgmentSource.MANUAL by an admin.
  4. Soft-delete protection: Refuses to resurrect a record sitting in the trash bin unless an operator restores it first.

Admin dashboard listing failed raw records pending review Figure 3. Admin failed-parse queue (/admin/raw-judgments?failed=true). Rejected payloads remain intact alongside the exact failure reason for operator inspection.


Integration test verification

I verify both idempotent reparsing and non-destructive error handling in a Spring Boot integration test:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// src/test/kotlin/com/example/server/judgment/JudgmentImportTest.kt
package com.example.server.judgment

import com.example.server.judgment.application.JudgmentImportService
import com.example.server.judgment.application.JudgmentParser
import com.example.server.judgment.domain.*
import com.example.server.support.IntegrationTestSupport
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import java.time.Instant
import java.time.LocalDate

class JudgmentImportTest : IntegrationTestSupport() {

    @Autowired lateinit var importer: JudgmentImportService
    @Autowired lateinit var raws: RawJudgmentJpaRepository
    @Autowired lateinit var judgments: JudgmentJpaRepository

    @Test
    fun `collect and reparse update the same judgment while preserving raw JSON and parser version`() {
        val serial = 219842L
        val rawPayload = """
            {
              "PrecService": {
                "precSerialNo": "219842",
                "caseNumber": "2021Do3451",
                "courtName": "Supreme Court",
                "sentenceDate": "20220819",
                "verdict": "Summary of fraud ruling",
                "fullText": "So ordered.\nJustice Jane Kim (Presiding) Alex Park Min Lee (Rapporteur)"
              }
            }
        """.trimIndent()

        // 1. Initial collection
        val firstResult = importer.collect(serial, rawPayload, Instant.now())
        assertThat(firstResult.error).isNull()

        val rawEntity = raws.findByPrecSerial(serial)!!
        assertThat(rawEntity.rawJson).isEqualTo(rawPayload)
        assertThat(rawEntity.parserVersion).isEqualTo(JudgmentParser.VERSION)

        // 2. Idempotent local reparse with zero external calls
        val reparseResult = importer.reparse(serial)
        assertThat(reparseResult.error).isNull()
        assertThat(reparseResult.judgmentId).isEqualTo(firstResult.judgmentId)

        // 3. Verify parsed domain fields
        val domain = judgments.findByPrecSerial(serial)!!
        assertThat(domain.caseNumber).isEqualTo("2021Do3451")
        assertThat(domain.judges).hasSize(3)
        assertThat(domain.judges.find { it.judge.name == "Jane Kim" }?.role).isEqualTo(JudgeRole.PRESIDING)
        assertThat(domain.judges.find { it.judge.name == "Min Lee" }?.rapporteur).isTrue()
    }

    @Test
    fun `corrupt raw payload logs parse error without overwriting existing valid judgment`() {
        val serial = 219843L
        val validPayload = """{"PrecService":{"precSerialNo":"$serial","caseNumber":"2023Do100","sentenceDate":"20231001"}}"""
        importer.collect(serial, validPayload)

        // Incoming payload with impossible calendar date (Feb 30)
        val corruptPayload = """{"PrecService":{"precSerialNo":"$serial","caseNumber":"2023Do100","sentenceDate":"20230230"}}"""
        val failedResult = importer.collect(serial, corruptPayload)

        assertThat(failedResult.error).contains("date")
        assertThat(raws.findByPrecSerial(serial)!!.parseError).isNotNull()
        // Existing domain record stays intact at 2023-10-01
        assertThat(judgments.findByPrecSerial(serial)!!.sentenceDate).isEqualTo(LocalDate.of(2023, 10, 1))
    }
}

Trade-offs and checklist

Storing raw payloads adds database storage overhead—in PostgreSQL, TOAST automatically compresses large TEXT columns, which keeps disk usage reasonable for tens or hundreds of thousands of JSON documents. Don’t store raw payloads in your primary OLTP table if you’re ingesting multi-terabyte streaming telemetry or strict PII that requires short retention windows; in those cases, archive raw files to S3/GCS with lifecycle policies and store only the object key in PostgreSQL.

Before adopting this pattern, run through this checklist:

  • Save raw JSON before parsing: Commit the raw record even when parsing fails so every bad payload stays inspectable.
  • Version your parser explicitly: Bump a constant like law-prec-v4 on every rule change so the reparse batch finds stale rows automatically.
  • Protect human edits: Never let an automated reparse overwrite manually curated or soft-deleted domain rows.
  • Keep collect() and reparse() on one code path: Sharing parseAndApply() guarantees that local reparses produce the exact same domain state as fresh API imports.
This post is licensed under CC BY 4.0 by the author.