본문으로 건너뛰기
cccskills
무료GitHub에 공개

kafka

Expert knowledge of Kafka event streaming patterns in melosys-api. Use when: (1) Understanding Kafka producers and consumers, (2) Debugging Kafka message processing issues, (3) Understanding topic configuration and message schemas, (4) Investigating SkippableKafkaErrorHandler and error handling, (5) Understanding Aiven Kafka setup and security configuration.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(2)

  • SKILL.md8.6 KB
  • references/debugging.md5.6 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Kafka Skill

Expert knowledge of Kafka event streaming patterns in melosys-api.

Quick Reference

Kafka Topics

TopicDirectionMessage TypePurpose
teammelosys.eessi.v1ConsumerMelosysEessiMeldingEESSI SED messages from EUX
teammelosys.soknad-mottak.v1ConsumerSoknadMottattA1 applications from Altinn
teammelosys.skattehendelser.v1ConsumerSkattehendelseTax events for årsavregning
teammelosys.manglende-fakturabetaling.v1ConsumerManglendeFakturabetalingMeldingMissing payments from faktureringskomponenten
teammelosys.melosys-hendelser.v1ProducerMelosysHendelseEvents to faktureringskomponenten
teammelosys.popp-hendelser.v1ProducerPensjonsopptjeningHendelsePension events to POPP
teammelosys.melosys-utstedt-a1.v1ProducerUtstedtA1MeldingA1 statistics to DVH

Key Components

All Kafka components live under integrasjon/src/main/kotlin/no/nav/melosys/integrasjon/kafka/.

ComponentPurpose
KafkaConfigProducer/consumer factory configuration
SkippableKafkaErrorHandlerError handling with skip capability
KafkaErrorControllerAdmin API (/admin/kafka/errors) for inspecting, retrying, and skipping failed messages
KafkaContainerServiceStarts stopped listener containers for a topic (internal service, called by KafkaErrorController)

Consumer Pattern

Standard Consumer Setup

@KafkaListener(
    clientIdPrefix = "aiven-melosys-xxx-consumer",
    topics = ["\${kafka.aiven.xxx.topic}"],
    containerFactory = "aivenXxxListenerContainerFactory"
)
@Transactional
fun handleMessage(consumerRecord: ConsumerRecord<String, MessageType>) {
    val message = consumerRecord.value()
    // Process message
}

Container Factory Pattern

Each message type has a dedicated container factory:

@Bean
fun aivenXxxListenerContainerFactory(
    objectMapper: ObjectMapper,
    kafkaProperties: KafkaProperties,
    @Value("\${kafka.aiven.xxx.groupid}") groupId: String
): KafkaConsumerContainerFactory<MessageType> =
    kafkaListenerContainerFactoryStopOnError<MessageType>(
        objectMapper, kafkaProperties, groupId
    )

Consumer Configuration

ConsumerConfig.GROUP_ID_CONFIG to groupId
ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG to false  // Manual ack
ConsumerConfig.AUTO_OFFSET_RESET_CONFIG to "earliest"
ConsumerConfig.MAX_POLL_RECORDS_CONFIG to 1  // One at a time

Producer Pattern

Standard Producer Setup

@Component
class KafkaXxxProducer(
    @Value("\${kafka.aiven.xxx.topic}") private val topicName: String,
    @Qualifier("xxxHendelse") private val kafkaTemplate: KafkaTemplate<String, MessageType>
) {
    fun send(message: MessageType) {
        val record = ProducerRecord<String, MessageType>(topicName, message)
        val future = kafkaTemplate.send(record)
        val result = future[15L, TimeUnit.SECONDS]
        log.info("Sent to $topicName, offset: ${result.recordMetadata.offset()}")
    }
}

Producer Factory Pattern

@Bean
fun producerFactoryXxx(objectMapper: ObjectMapper): ProducerFactory<String, MessageType> =
    DefaultKafkaProducerFactory(
        mutableMapOf<String, Any>(
            CommonClientConfigs.CLIENT_ID_CONFIG to "melosys-xxx-producer",
            ProducerConfig.ACKS_CONFIG to "all",
            ProducerConfig.BOOTSTRAP_SERVERS_CONFIG to brokersUrl,
        ) + securityConfig(),
        StringSerializer(),
        JsonSerializer(objectMapper)
    )

Error Handling

SkippableKafkaErrorHandler

Custom error handler that:

  1. Stops container on error (CommonContainerStoppingErrorHandler)
  2. Stores failed messages for inspection
  3. Allows manual skip of problematic messages
@Component
class SkippableKafkaErrorHandler : CommonContainerStoppingErrorHandler() {
    val failedMessages = ConcurrentHashMap<String, Failed>()

    // Key format: "topic-partition-offset"
    fun markToSkip(key: String): Boolean
}

Failed Message Structure

data class Failed(
    val topic: String,
    val offset: Long?,
    val partition: Int?,
    val record: Map<String, Any?>?,
    val rawMessage: String?,
    val errorStack: String?
)

Admin API Endpoints

All endpoints live under KafkaErrorController at base path /admin/kafka/errors (@Protected). Failed-message keys use the format topic-partition-offset.

GET /admin/kafka/errors
# Lists failed messages for this pod. Returns {podName, errors}
# where errors is a map of key -> Failed (topic, offset, partition, record, rawMessage, errorStack)

POST /admin/kafka/errors/{key}/retry
# Removes the stored error and, if the topic's container is stopped, restarts it
# so the message is reprocessed from its offset

DELETE /admin/kafka/errors/{key}
# Skip: marks the message to be skipped next time it's seen, removes it from the
# failed cache, and restarts the topic's container if stopped (NOTE: DELETE, not POST)

POST /admin/kafka/errors/resume-all
# Clears all failed messages grouped per topic and restarts each topic's stopped container

Errors are held in-memory per pod, so a GET reports only the pod it hit. There are no container start/stop/list endpoints — container restarts happen as a side effect of retry, skip, and resume-all via KafkaContainerService.

Security Configuration

Aiven SSL Setup

private fun securityConfig(): Map<String, Any> =
    if (isLocal) mapOf() else mapOf(
        SECURITY_PROTOCOL_CONFIG to "SSL",
        SSL_TRUSTSTORE_LOCATION_CONFIG to truststorePath,
        SSL_TRUSTSTORE_PASSWORD_CONFIG to credstorePassword,
        SSL_TRUSTSTORE_TYPE_CONFIG to "JKS",
        SSL_KEYSTORE_LOCATION_CONFIG to keystorePath,
        SSL_KEYSTORE_PASSWORD_CONFIG to credstorePassword,
        SSL_KEY_PASSWORD_CONFIG to credstorePassword,
        SSL_KEYSTORE_TYPE_CONFIG to "PKCS12"
    )

Local Development

For local profiles (local, local-mock, test), security is disabled and connects to local Kafka.

Message Types

MelosysEessiMelding (Consumer)

EESSI messages from EUX containing SED documents.

SoknadMottatt (Consumer)

A1 applications from Altinn skjema-api.

Skattehendelse (Consumer)

Tax events from melosys-skattehendelser for årsavregning.

ManglendeFakturabetalingMelding (Consumer)

Missing payment notifications from faktureringskomponenten.

MelosysHendelse (Producer)

Events sent to faktureringskomponenten for billing.

PensjonsopptjeningHendelse (Producer)

Pension registration events sent to POPP.

UtstedtA1Melding (Producer)

A1 statistics sent to DVH.

Debugging

When a consumer hits an error, SkippableKafkaErrorHandler stops the container, so symptoms are "messages stop being processed" rather than a crash.

View Failed Messages

GET /admin/kafka/errors

Retry, Skip, or Resume

# Retry a single message (restarts the stopped container)
POST /admin/kafka/errors/teammelosys.eessi.v1-0-12345/retry

# Skip a poison message, then the container restarts and resumes at offset+1
DELETE /admin/kafka/errors/teammelosys.eessi.v1-0-12345

# Clear every failed message per topic and restart all stopped containers
POST /admin/kafka/errors/resume-all

Kafka UI

Local development: http://localhost:8087

For container-stopped / deserialization / SSL troubleshooting and log patterns, see references/debugging.md.

Testing

Integration Test Pattern

@KafkaListener(
    topics = ["\${kafka.aiven.xxx.topic}"],
    groupId = "\${kafka.aiven.xxx.groupid}",
    containerFactory = "xxxListenerContainerFactory"
)
private fun testListener(record: ConsumerRecord<String, MessageType>) {
    records.add(record)
}

fun waitForMessage(timeout: Duration): MessageType? =
    records.poll(timeout.toMillis(), TimeUnit.MILLISECONDS)?.value()

KafkaOffsetChecker

Utility for waiting until consumer has caught up:

kafkaOffsetChecker.waitForConsumerToCatchUp(topic, groupId, timeout)

Related Skills

  • eessi-eux: EESSI message processing
  • altinn-soknad: Application message processing
  • inntekt-skatt: Tax event processing
  • trygdeavgift: Billing message handling
  • statistikk: A1 statistics publishing

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Expert knowledge of Altinn A1 application processing for posted workers in melosys-api. Use when: (1) Understanding Altinn søknad/skjema processing, (2) Debugging MedlemskapArbeidEOS form mapping, (3) Understanding SoeknadMapper transformations, (4) Investigating posted worker application issues, (5) Understanding the MOTTAK_SOKNAD_ALTINN saga flow.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Expert knowledge of Employer/Employment integration (EREG/AAREG) in melosys-api. Use when: (1) Working with organization data from EREG (Enhetsregisteret), (2) Working with employment data from AAREG (Arbeidsforhold), (3) Understanding employer/organization lookup, (4) Debugging employer or employment issues, (5) Understanding the mapping between register data and domain models. Triggers: orgnummer, arbeidsforhold, EREG, AAREG, Enhetsregisteret, registeropplysninger, ansettelsesperiode, saksopplysning.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Modular monolith architecture overview for melosys-api. Use when needing to understand module structure, dependencies between modules, where to place new code, or when changes in one module might affect others. Triggers: "architecture", "module dependencies", "where should I put", "which modules", "dependency graph".

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Expert knowledge of Behandling (case treatment) domain in melosys-api. Use when: (1) Understanding the behandling lifecycle and status transitions, (2) Debugging issues with behandling creation, status changes, or closure, (3) Understanding relationships between Fagsak, Behandling, and Behandlingsresultat, (4) Investigating why a behandling is stuck or has wrong status, (5) Understanding Behandlingstyper, Behandlingstema, Behandlingsstatus enums, (6) Debugging journalføring or SED-triggered behandling creation, (7) Understanding behandling creation via saksflyt sagas.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Expert knowledge of Behandlingsresultat (treatment result) domain in melosys-api. Use when: (1) Understanding result types and their meaning (FASTSATT_LOVVALGSLAND, MEDLEM_I_FOLKETRYGDEN, etc.), (2) Working with periods - Lovvalgsperiode, Medlemskapsperiode, Anmodningsperiode, Utpekingsperiode, (3) Debugging vedtak/decision metadata, criteria evaluation, or social insurance charges, (4) Understanding EU/EEA coordination logic and Article 16 exception handling, (5) Working with trygdeavgift (social insurance charge) calculations.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

brev

무료

Expert knowledge of Brev (letter generation) in melosys-api. Use when: (1) Producing letters and decision documents (vedtaksbrev), (2) Understanding Dokgen templates and mapping, (3) Configuring letter recipients and distribution, (4) Debugging letter generation issues, (5) Adding new letter types or templates.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

navikt의 스킬 모두 보기

이 스킬의 문제 신고