diff --git a/patroni/__main__.py b/patroni/__main__.py
index 1ceaa2913..cc8210794 100644
--- a/patroni/__main__.py
+++ b/patroni/__main__.py
@@ -259,7 +259,9 @@ def _run_cycle(self) -> None:
         if self.postgresql.role != PostgresqlRole.UNINITIALIZED:
             self.config.save_cache()
 
-        self.schedule_next_run()
+        # Don't wait for the next cycle if SIGTERM was received while running the current one.
+        if not self.received_sigterm:
+            self.schedule_next_run()
 
     def _shutdown(self) -> None:
         """Perform shutdown of ``patroni`` daemon process.
diff --git a/patroni/api.py b/patroni/api.py
index ccc85e8f2..07271e7ec 100644
--- a/patroni/api.py
+++ b/patroni/api.py
@@ -1939,6 +1939,16 @@ def finish_request(self, request: Union[socket.socket, Tuple[bytes, socket.socke
         except OSError as e:
             logger.debug('Connection from %s:%s was reset: %r', client_address[0], client_address[1], e)
 
+    def service_actions(self) -> None:
+        """Wake up the HA loop if SIGTERM was received.
+
+        Called by :func:`~socketserver.BaseServer.serve_forever` every 0.5 seconds. The SIGTERM handler can't do it
+        itself, because it must not acquire locks.
+        """
+        super(RestApiServer, self).service_actions()
+        if self.patroni.received_sigterm:
+            self.patroni.ha.wakeup()
+
     def shutdown(self) -> None:
         super(RestApiServer, self).shutdown()
         self._executor.shutdown(wait=True)
diff --git a/patroni/daemon.py b/patroni/daemon.py
index ecc20d152..ba212bf10 100644
--- a/patroni/daemon.py
+++ b/patroni/daemon.py
@@ -125,25 +125,51 @@ def api_sigterm(self) -> bool:
     def sigterm_handler(self, *_: Any) -> None:
         """Handle SIGTERM signals.
 
-        Terminate the daemon process through :func:`api_sigterm`.
+        Terminate the daemon process until :func:`enable_graceful_sigterm` is called. Afterwards only flag the daemon
+        as "SIGTERM received", the main loop exits and shuts down the daemon. If the main loop doesn't exit within
+        ``loop_wait`` seconds, for example because it hangs, :func:`sigalrm_handler` terminates the daemon process.
+
+        .. note::
+            Python runs signal handlers in the main thread between arbitrary bytecode instructions. An exception
+            raised here could leave a lock held by the interrupted code locked forever, and the shutdown would
+            deadlock on it. The handler must not acquire locks either, because the interrupted code could hold them.
+        """
+        if not self._received_sigterm:
+            self._received_sigterm = True
+            if not self._graceful_sigterm:
+                sys.exit()
+            if self._main_loop_running and os.name != 'nt':
+                signal.alarm(self.config['loop_wait'])
+
+    def sigalrm_handler(self, *_: Any) -> None:
+        """Handle SIGALRM signals.
+
+        Terminate the daemon process if the main loop is still running, i.e. it didn't exit in time after SIGTERM.
         """
-        if self.api_sigterm():
+        if self._main_loop_running:
             sys.exit()
 
+    def enable_graceful_sigterm(self) -> None:
+        """Make :func:`sigterm_handler` only flag the daemon as "SIGTERM received" instead of terminating it."""
+        self._graceful_sigterm = True
+
     def setup_signal_handlers(self) -> None:
         """Set up daemon signal handlers.
 
-        Set up SIGHUP and SIGTERM signal handlers.
+        Set up SIGHUP, SIGALRM and SIGTERM signal handlers.
 
         .. note::
 
-            SIGHUP is only handled in non-Windows environments.
+            SIGHUP and SIGALRM are only handled in non-Windows environments.
         """
         self._received_sighup = False
         self._sigterm_lock = Lock()
         self._received_sigterm = False
+        self._graceful_sigterm = False
+        self._main_loop_running = False
         if os.name != 'nt':
             signal.signal(signal.SIGHUP, self.sighup_handler)
+            signal.signal(signal.SIGALRM, self.sigalrm_handler)
         signal.signal(signal.SIGTERM, self.sigterm_handler)
 
     @property
@@ -177,13 +203,20 @@ def run(self) -> None:
         """
         notify_systemd("READY=1")
         self.logger.start()
-        while not self.received_sigterm:
-            if self._received_sighup:
-                self._received_sighup = False
-                self.reload_config(True, self.config.reload_local_configuration())
-                notify_systemd("READY=1")
-
-            self._run_cycle()
+        self._main_loop_running = True
+        try:
+            while not self.received_sigterm:
+                if self._received_sighup:
+                    self._received_sighup = False
+                    self.reload_config(True, self.config.reload_local_configuration())
+                    notify_systemd("READY=1")
+
+                self._run_cycle()
+        finally:
+            # SIGALRM must neither interrupt the shutdown nor kill the process after Python restores default handlers
+            self._main_loop_running = False
+            if os.name != 'nt':
+                signal.alarm(0)
 
     @abc.abstractmethod
     def _shutdown(self) -> None:
@@ -238,6 +271,7 @@ def abstract_main(cls: Type[AbstractPatroniDaemon], configfile: str) -> None:
         logger.warning('Failed to set threading.stack_size(%s): %r', thread_stack_size, e)
 
     controller = cls(config, patroni_logger)
+    controller.enable_graceful_sigterm()
     try:
         controller.run()
     except KeyboardInterrupt:
diff --git a/tests/test_api.py b/tests/test_api.py
index 40bc1c44a..5b888ac5c 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -175,6 +175,8 @@ def sighup_handler():
     def api_sigterm():
         pass
 
+    received_sigterm = False
+
 
 class MockRequest(object):
 
@@ -848,6 +850,14 @@ def test_server_bind(self, mock_getfqdn):
             self.srv.server_bind()
         mock_getfqdn.assert_not_called()
 
+    @patch.object(MockHa, 'wakeup')
+    def test_service_actions(self, mock_wakeup):
+        self.srv.service_actions()
+        mock_wakeup.assert_not_called()
+        with patch.object(MockPatroni, 'received_sigterm', True):
+            self.srv.service_actions()
+        mock_wakeup.assert_called_once()
+
     @patch.object(HTTPServer, '__init__', Mock())
     def test_reload_config(self):
         bad_config = {'listen': 'foo'}
diff --git a/tests/test_patroni.py b/tests/test_patroni.py
index 00f16b2cd..d7ba3480a 100644
--- a/tests/test_patroni.py
+++ b/tests/test_patroni.py
@@ -203,6 +203,43 @@ def test_run(self):
     def test_sigterm_handler(self):
         self.assertRaises(SystemExit, self.p.sigterm_handler)
 
+    def test_api_sigterm(self):
+        self.assertTrue(self.p.api_sigterm())
+        self.assertFalse(self.p.api_sigterm())
+        self.p.sigterm_handler()  # doesn't raise SystemExit, because SIGTERM was already received
+
+    @patch('signal.alarm', create=True)
+    @patch('patroni.config.Config.save_cache', Mock())
+    @patch('patroni.config.Config.set_dynamic_configuration', Mock(return_value=False))
+    @patch.object(Postgresql, 'reload_config', Mock())
+    def test_graceful_sigterm(self, mock_alarm):
+        self.p.enable_graceful_sigterm()
+        self.p.api.start = Mock()
+        self.p.logger.start = Mock()
+        self.p.ha.dcs.watch = Mock(side_effect=SleepException)
+
+        def run_cycle():
+            self.p.sigterm_handler()  # doesn't raise SystemExit anymore
+            return 'no action'
+
+        # the main loop exits after the HA cycle, during which SIGTERM was received, without waiting for the next one
+        self.p.ha.run_cycle = Mock(side_effect=run_cycle)
+        self.p.run()
+        self.assertTrue(self.p.received_sigterm)
+        self.p.ha.dcs.watch.assert_not_called()
+        # the alarm is armed on SIGTERM and canceled when the main loop exits
+        loop_wait = self.p.config['loop_wait']
+        self.assertEqual(mock_alarm.call_args_list, [] if os.name == 'nt' else [((loop_wait,),), ((0,),)])
+
+    def test_sigalrm_handler(self):
+        self.p.sigalrm_handler()  # doesn't raise SystemExit before the main loop has started
+        self.p.api.start = Mock()
+        self.p.logger.start = Mock()
+        # the main loop is stuck in the HA cycle when SIGALRM arrives
+        self.p.ha.run_cycle = Mock(side_effect=self.p.sigalrm_handler)
+        self.assertRaises(SystemExit, self.p.run)
+        self.p.sigalrm_handler()  # doesn't raise SystemExit after the main loop has exited
+
     def test_schedule_next_run(self):
         self.p.ha.cluster = Mock()
         self.p.ha.dcs.watch = Mock(return_value=True)
