Skip to content

Quit gracefully on interrupt #1391

Closed
Closed
@HannesP

Description

@HannesP

I have a service which reads from a Kafka topic using KafkaConsumer. When the service receives a SIGTERM, I want to shut it down gracefully. However, I can't find a way to stop the consumer without causing an error. This is my approach:

import signal

def sigterm_handler(signo, frame):
	consumer.close()
signal.signal(signal.SIGTERM, sigterm_handler)

consumer = KafkaConsumer('my-topic')
for msg in consumer:
	process_message(msg)

I've also tried this approach, but since the topic may be written to very rarely, it isn't useful for shutting the service down:

import signal

has_stopped = False
def sigterm_handler(signo, frame):
	has_stopped = True
signal.signal(signal.SIGTERM, sigterm_handler)

consumer = KafkaConsumer('my-topic')
for msg in consumer:
	if has_stopped:
		break
	process_message(msg)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions