Automatic Restart of a Trading Bot: systemd, Docker, Alerts

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Automatic Restart of a Trading Bot: systemd, Docker, Alerts
Simple
~1 day
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Configuring Automatic Restart of a Trading Bot

A trading bot runs 24/7. A crash due to a network error, OOM, unhandled exception, or system update — and the process dies. Without auto-restart, the bot stays dead until an operator intervenes. The longer the downtime, the more missed profit and risk of missing trading signals. In production, we achieve 99.9% uptime using a combination of systemd, graceful shutdown, and alerts. We'll show how to set this up using a real project example: a Python bot with aiohttp running on Ubuntu 22.04 with 4 cores. We use systemd for management, Docker for isolation, and Prometheus for monitoring.

systemd is the standard service manager on Linux. It can automatically restart a process, limit resources, and log. But simply setting Restart=always isn't enough — you need protection against crash loops. Let's look at three key components: the systemd unit, graceful shutdown in the bot code, and alerts on failures. For containerized bots, we supplement with Docker restart policy and health checks.

How to Configure systemd for Automatic Restart

Create a unit file in /etc/systemd/system/ with Restart=always and RestartSec=10. Additionally set StartLimitBurst=5 and StartLimitIntervalSec=60 to avoid infinite restarts on critical errors. Enable the service: systemctl enable trading-bot.

# /etc/systemd/system/trading-bot.service

[Unit]
Description=Trading Bot
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=botuser
WorkingDirectory=/opt/trading-bot
ExecStart=/opt/trading-bot/venv/bin/python -u bot.py
Restart=always
RestartSec=10
StartLimitIntervalSec=60
StartLimitBurst=5

EnvironmentFile=/opt/trading-bot/.env
MemoryLimit=2G
CPUQuota=80%

StandardOutput=journal
StandardError=journal
SyslogIdentifier=trading-bot

[Install]
WantedBy=multi-user.target

Activation:

systemctl daemon-reload
systemctl enable trading-bot
systemctl start trading-bot
journalctl -u trading-bot -f   # live logs

The parameters StartLimitBurst=5 + StartLimitIntervalSec=60 provide protection against crash loops. Without them, a bot that keeps crashing would restart indefinitely, accumulating errors (open positions, duplicate orders). After 5 quick crashes, systemd stops the service and triggers an alert (if configured). This is 5 times more reliable than a simple cron monitor.

systemd Unit Parameters: Detailed Breakdown

Parameter Description Example
Restart Restart policy always
RestartSec Pause between restarts 10
StartLimitBurst Limit of fast restarts 5
StartLimitIntervalSec Interval for the limit 60
MemoryLimit Memory limit 2G
CPUQuota CPU quota 80%

These parameters increase stability: the bot doesn't crash from overloads, and on frequent errors, systemd blocks startup, preventing losses due to double orders.

What Is Graceful Shutdown and Why Is It Needed?

You cannot kill a bot with SIGKILL — it may leave open orders, uncommitted positions, unsent alerts. Handle SIGTERM:

import signal
import asyncio

class TradingBot:
    def __init__(self):
        self.running = True
        self.open_orders: list = []

    async def shutdown(self):
        self.running = False
        for order_id in self.open_orders:
            try:
                await self.exchange.cancel_order(order_id)
            except Exception as e:
                logger.error(f"Failed to cancel order {order_id}: {e}")
        logger.info("Graceful shutdown complete")

    async def run(self):
        loop = asyncio.get_event_loop()
        loop.add_signal_handler(
            signal.SIGTERM,
            lambda: asyncio.create_task(self.shutdown())
        )

        while self.running:
            try:
                await self.main_loop()
            except Exception as e:
                logger.exception(f"Error in main loop: {e}")
                await asyncio.sleep(5)

systemd on systemctl stop sends SIGTERM, then after TimeoutStopSec (default 90 sec) sends SIGKILL. For a bot with positions, 90 seconds is usually sufficient.

Docker: An Alternative for Containerized Bots

If the bot runs in Docker, use restart: unless-stopped — it restarts on crash and after host reboot, but not on manual stop. A health check is critical: Docker only restarts a container on a complete crash; a hang without an error goes unnoticed.

# docker-compose.yml
services:
  trading-bot:
    image: trading-bot:latest
    restart: unless-stopped
    env_file: .env
    volumes:
      - ./data:/app/data
      - ./logs:/app/logs
    mem_limit: 2g
    logging:
      driver: "json-file"
      options:
        max-size: "100m"
        max-file: "5"
    healthcheck:
      test: ["CMD", "python", "-c", "import requests; requests.get('http://localhost:8080/health', timeout=5)"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 60s

Example health endpoint on aiohttp:

from aiohttp import web

async def health_check(request):
    last_loop_age = time.time() - bot.last_loop_time
    if last_loop_age > 300:
        return web.Response(status=503, text=f"Bot stuck: last loop {last_loop_age:.0f}s ago")
    if not bot.exchange_connected:
        return web.Response(status=503, text="Exchange disconnected")
    return web.Response(status=200, text="OK")

app = web.Application()
app.router.add_get('/health', health_check)

Comparison of systemd and Docker for Auto-Restart

Parameter systemd Docker
Restart mechanism systemd unit restart policy
Crash loop protection StartLimitBurst + Interval None built-in (only health)
Graceful shutdown SIGTERM + TimeoutStopSec SIGTERM + stop_grace_period
Hang monitoring None built-in Health check
Recommendation For own Linux servers For containerized infrastructure

Why Alerts on Crash Are Needed

The fact of a restart should generate a notification — even if the bot recovered automatically. The minimal solution is a Telegram bot with the hostname and time. In systemd, this is done via OnFailure=trading-bot-notify.service. For Prometheus: rule changes(process_start_time_seconds{job="trading-bot"}[5m]) > 0. Get a consultation on alert configuration — we'll recommend the optimal solution for your infrastructure.

What’s Included in Auto-Restart Configuration (Deliverables)

  • systemd unit or Docker Compose configuration with crash loop protection
  • Implementation of graceful shutdown handling open orders
  • Health check endpoint verifying bot and exchange state
  • Alert configuration (Telegram / Slack) on crashes and frequent restarts
  • Testing on a staging environment before production deployment
  • Configuration documentation and instructions for your team
  • 5+ years of experience in blockchain development — we guarantee stability
Example crash loop and its consequences

If the bot crashes every 5 seconds due to an exchange connection error, without StartLimitBurst systemd will restart it indefinitely. Each startup may try to cancel orders or create new ones, leading to double positions. With StartLimitBurst=5 after the fifth attempt, systemd stops the service, and you receive an alert. This saves you from financial losses.

Contact us to set up your trading bot — we ensure 24/7 stable operation. Get a consultation on systemd, Docker, and alert configuration.

Blockchain Infrastructure Deployment: Nodes, RPC, Indexing

Subgraph fell at 3:47 AM. By morning users saw outdated balances, transactions "hung" in the UI, support received 47 tickets in an hour. Cause: the handler in the subgraph failed on a transaction with a non-standard event log — and the entire index stopped. We have encountered such situations dozens of times. Our experience shows: blockchain infrastructure does not forgive gaps in observability. Guaranteeing uptime without multi-layered monitoring and fault-tolerant architecture is impossible. Over 8 years working with Ethereum, Polygon, and Solana, we have developed an approach that allows predictable deployment of infrastructure of any scale — from a single node to a multichain grid with dozens of subgraphs.

RPC Layer Architecture

Every dApp interaction with the blockchain goes through RPC — the JSON-RPC API provided by a node. Three options:

Managed providers — Alchemy, QuickNode, Infura, Ankr. Minimal operational costs, SLA, built-in monitoring. Limits: rate limits (Alchemy Free: 300 RU/sec), vendor lock, potential downtime during provider incidents. For most projects — the right choice at the start.

Self-owned nodes — full control, no rate limits, no third-party dependence. Cost: archive Ethereum node requires 2.5–3TB SSD, a strong server, and DevOps support. Sync from scratch on Ethereum via Geth/Nethermind — 3–7 days. Justified under high load or latency requirements.

Hybrid — self-owned node as primary, managed provider as fallback. Standard for protocols with high TVL. Proper load balancing can reduce costs by 20–30% compared to pure managed setup. Under high monthly request volume, hybrid saves significantly.

Provider Strength Limitation
Alchemy Supernode, Enhanced APIs, webhooks Expensive on high-volume
QuickNode Low latency, multi-chain More expensive than Alchemy on basic plan
Infura Historical reliability Rate limits on free, one major incident halted half of DeFi
Ankr Cheap, 40+ chains Less stable

How to Set Up an RPC Layer Without a Single Point of Failure?

At least two providers, DNS round-robin with health check every 5 seconds, automatic fallback when latency >500 ms. In practice, this gives 99.99% availability during any provider failure. For protocols with high TVL, we recommend a custom HA-proxy (nginx or Envoy) in front of two managed providers.

Why Is a Hybrid RPC Scheme More Cost-Effective Than Pure Managed?

At high request volumes, managed providers can be very expensive; a hybrid using a self-owned node as primary and a managed fallback cuts costs significantly without losing SLA.

Ethereum Node Clients

Execution clients: Geth (most used), Nethermind (C#, fast sync), Besu (Java, enterprise), Erigon (fastest sync, efficient archive mode ~2TB instead of 3TB).

Consensus clients (post-Merge): Lighthouse (Rust), Prysm (Go), Teku (Java), Nimbus (Nim). Each node after The Merge requires a pair of execution + consensus clients.

For DevOps: eth-docker — Docker Compose configurations for all client combinations. Setting up monitoring via Grafana + Prometheus is mandatory; a standard dashboard is available in each client's repository.

The Graph: Event Indexing

The Graph Protocol — decentralized indexing. A subgraph describes which events from which contracts to index and how to transform them into a GraphQL schema.

Subgraph structure:

  • subgraph.yaml — manifest: contract addresses, startBlock, events to handle
  • schema.graphql — GraphQL schema of entities
  • src/mapping.ts — AssemblyScript event handlers
dataSources:
  - kind: ethereum
    name: UniswapV3Pool
    network: mainnet
    source:
      address: "0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640"
      abi: UniswapV3Pool
      startBlock: 12370624
    mapping:
      eventHandlers:
        - event: Swap(indexed address,indexed address,int256,int256,uint160,uint128,int24)
          handler: handleSwap

AssemblyScript handlers — not TypeScript. No nullable types, no closures, no many standard APIs. An error in the handler stops the subgraph indexing on that transaction. Important: add try-catch for operations that can fail (e.g., store.get() for an entity that may not exist).

How to Avoid Subgraph Indexing Stops?

Graph Node logs are monitored in real-time; on hasIndexingErrors = true an alert fires and an automatic node restart (via systemd or Kubernetes). Typical downtime on error — 150–300 seconds to recover. Additionally, for production we set up a watchdog that restarts Graph Node if subgraph lag exceeds 50 blocks.

Choosing Between Hosted Service and Decentralized Network

Graph Hosted Service (free, centralized) is deprecated in favor of Subgraph Studio + Graph Network. For production: deploy on Graph Network with GRT curation signal — the subgraph gets indexers proportional to curation.

Alternatives to The Graph: Ponder (TypeScript, self-hosted, easier to debug), Envio (ultra-fast indexer, supports EVM + non-EVM), Subsquid (TypeScript, own network), Moralis Streams (managed, webhook-based). Our experience shows: for high-load projects with unique logic, Ponder or Envio are more effective — they give full control over the process and do not require GRT tokenomics.

Webhooks and Real-Time Notifications

Alchemy Webhooks and QuickNode Streams allow receiving events in real-time via HTTP webhook or WebSocket. For monitoring addresses, new transactions, mints — this is faster than polling RPC.

Tenderly — platform for monitoring and alerts. You can set up an alert for a specific contract event, balance change, function call with certain parameters. Transaction simulation via Tenderly API is invaluable for debugging.

Monitoring and Observability

Minimum monitoring stack for a protocol:

On-chain: OpenZeppelin Defender Sentinel — watches contract events, triggers webhook or Autotask when conditions are met. Forta Network — community-maintained bots detect anomalies (large withdrawals, flash loans, governance attacks).

Infrastructure: Grafana + Prometheus for nodes, Datadog or Grafana Cloud for managed metrics. Alerts on: node is 10+ blocks behind, RPC latency >500ms, subgraph lag >100 blocks.

Uptime: Better Uptime or PagerDuty on RPC endpoint and subgraph health endpoint (The Graph provides _meta { hasIndexingErrors, block { number } }).

Why Is Monitoring Without Tenderly Insufficient?

Tenderly provides transaction simulation and detailed traces — critical for debugging subgraph and smart contract errors. Forta focuses on network anomalies, not your infrastructure. The combination of Tenderly plus a custom Grafana dashboard covers 90% of incident scenarios.

Multichain Infrastructure

A protocol on 5 chains = 5 separate RPC endpoints, 5 subgraphs, 5 monitoring configs. Manageable but requires deployment automation.

For subgraph multi-network deployment: graph deploy --network mainnet, graph deploy --network arbitrum-one etc. with a unified codebase and network-specific addresses in separate config files.

Chainlink CCIP and LayerZero for cross-chain messaging require monitoring of both chains and transactions on intermediate relayers. A reorg on the source chain after a confirmed mint on the target chain is a classic bridge problem. Solution: wait for finality (on Ethereum ~15 minutes after Merge for economic finality) before confirming on the target chain.

Infrastructure Setup Process

  1. Audit current stack — determine chains, request volume, latency and availability requirements.
  2. Architecture design — select providers, load balancing, redundancy.
  3. Subgraph development — manifest → schema → handlers → testing on local Graph Node → deploy to testnet → mainnet.
  4. Monitoring configuration — Tenderly alerts, Grafana dashboard, PagerDuty integration.
  5. Documentation and runbook — what to do when: subgraph falls behind, RPC downtime, node desync.
  6. Handover to operations — team training, access transfer, first month support.

What's Included

  • Deployment of managed or self-hosted Ethereum, Polygon, BNB Chain nodes
  • RPC layer setup with primary/fallback and load balancing
  • Subgraph development and deployment for your protocol
  • Monitoring connection (Tenderly, Grafana, alerts)
  • Runbook and operations documentation
  • Team training (up to 4 hours online)
  • 30-day support after delivery

Timeline

Task Duration
RPC and basic monitoring setup 1–2 weeks
Subgraph for one protocol 2–4 weeks
Self-hosted node with monitoring 2–3 weeks
Full infrastructure (multi-chain, monitoring, runbooks) 6–10 weeks

All projects are managed in a GitHub/GitLab repository with CI/CD; configuration code stays with you. Order infrastructure deployment — we'll show how to cut costs by 20–30% without losing reliability. Get a consultation — we'll demonstrate how we deployed infrastructure for a protocol with large TVL on Ethereum and Arbitrum. Contact us.