Telego Long Polling Configuration Options: Complete Guide for Go Bots

Telego provides three functional options—WithLongPollingUpdateInterval, WithLongPollingRetryTimeout, and WithLongPollingBuffer—to control request throttling, error recovery, and update throughput when receiving Telegram updates via the UpdatesViaLongPolling method.

The mymmrac/telego library implements the Telegram Bot API in Go, using long polling to fetch updates through repeated GetUpdates calls. Understanding the available Telego long polling configuration options allows developers to optimize bot performance, handle network instability, and manage high-throughput scenarios by modifying the internal longPolling struct behavior.

Core Configuration Options

Telego exposes tuning parameters through functional options that mutate the longPolling struct defined in long_polling.go:20-25. Each option controls a specific aspect of the polling lifecycle.

Throttling Requests with WithLongPollingUpdateInterval

WithLongPollingUpdateInterval(duration) sets the minimum delay between successful GetUpdates calls. This prevents overwhelming the Telegram API or intermediary proxies when your bot requires rate limiting.

  • Default: 0s (no artificial delay)
  • Use case: Deployments behind corporate proxies with strict request quotas

Handling Network Failures with WithLongPollingRetryTimeout

WithLongPollingRetryTimeout(duration) specifies how long to wait after a failed GetUpdates attempt before retrying. If set to 0, the polling loop terminates immediately upon error and closes the update channel.

  • Default: 8s
  • Implementation: The loop sleeps via time.Sleep(lp.retryTimeout) as shown in long_polling.go:28-34
  • Use case: Transient network outages where immediate retry risks cascading failures

Managing Throughput with WithLongPollingBuffer

WithLongPollingBuffer(size) defines the capacity of the buffered channel that delivers Update objects. Larger buffers decouple the polling loop from slow consumers, preventing head-of-line blocking.

  • Default: 100
  • Use case: Bots processing computationally intensive updates or experiencing bursty traffic patterns

Implementation Details in Source Code

The long-polling mechanism resides primarily in long_polling.go, with lifecycle management centralized in bot.go.

Default Timeout Injection

When UpdatesViaLongPolling receives nil for GetUpdatesParams, Telego automatically injects a default timeout of 8 seconds (defaultLongPollingUpdateTimeoutInSeconds). This value is set in long_polling.go:91-95 and aligns with Telegram’s recommended long-polling behavior.

Offset Management and Context Preservation

After each successful GetUpdates call, the loop updates the offset parameter to lastUpdateID + 1 to prevent duplicate delivery. Each Update is wrapped with the caller-provided context via Update.WithContext before being sent to the channel, as implemented in long_polling.go:36-48.

Concurrency Safety

The Bot.run method in bot.go:71-84 ensures that only one update mode (long-polling or webhook) runs concurrently. Attempting to start long-polling while another mode is active returns an error, preventing resource contention and API conflicts.

Practical Usage Example

The following example demonstrates configuring all three options when initializing a bot:

package main

import (
    "context"
    "time"

    "github.com/mymmrac/telego"
)

func main() {
    // Initialize bot with your token
    bot, err := telego.NewBot("YOUR_BOT_TOKEN")
    if err != nil {
        panic(err)
    }

    // Create cancellable context for graceful shutdown
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    // Configure long-polling options
    opts := []telego.LongPollingOption{
        telego.WithLongPollingUpdateInterval(2 * time.Second),
        telego.WithLongPollingRetryTimeout(5 * time.Second),
        telego.WithLongPollingBuffer(200),
    }

    // Start receiving updates; nil params use default 8s timeout
    updates, err := bot.UpdatesViaLongPolling(ctx, nil, opts...)
    if err != nil {
        bot.Logger().Fatalf("Failed to start long-polling: %s", err)
    }

    // Process updates
    for update := range updates {
        // Handle update with preserved context
        processUpdate(update)
    }
}

func processUpdate(update telego.Update) {
    // Implementation details...
}

Common Configuration Scenarios

Choose your Telego long polling configuration options based on operational constraints:

  • Maximum throughput: Use defaults (0s interval, 8s retry, 100 buffer) for minimal latency between Telegram and your handler.
  • Rate-limited proxies: Set WithLongPollingUpdateInterval(1 * time.Second) to enforce a minimum delay between successful API calls.
  • Resilient deployments: Increase WithLongPollingRetryTimeout(10 * time.Second) to back off during transient network failures.
  • Bursty traffic: Expand WithLongPollingBuffer(500) to absorb spikes without blocking the polling loop.
  • Fail-fast monitoring: Set WithLongPollingRetryTimeout(0) to terminate immediately on errors, allowing external orchestrators to detect failures.

Summary

  • Telego long polling configuration options are functional options that modify the internal longPolling struct before the polling loop starts.
  • WithLongPollingUpdateInterval throttles successful requests, defaulting to 0s for immediate subsequent calls.
  • WithLongPollingRetryTimeout controls error recovery sleep duration (8s default); set to 0 to disable retries.
  • WithLongPollingBuffer sizes the update channel (100 default), tuning back-pressure between the poller and consumer.
  • The implementation in long_polling.go and bot.go manages context propagation, offset tracking, and concurrent mode prevention.

Frequently Asked Questions

What is the default timeout for GetUpdates in Telego long polling?

When you pass nil for GetUpdatesParams to UpdatesViaLongPolling, Telego automatically applies a default timeout of 8 seconds (defaultLongPollingUpdateTimeoutInSeconds). This value is injected in long_polling.go:91-95 and aligns with Telegram’s recommended long-polling behavior to reduce empty responses.

How do I stop the bot from retrying on network errors?

Set WithLongPollingRetryTimeout(0) when calling UpdatesViaLongPolling. According to the implementation in long_polling.go:28-34, a zero value disables the sleep-and-retry mechanism. When an error occurs, the polling loop terminates immediately and closes the updates channel, allowing your application to detect the failure via channel closure.

What happens if I start long polling while a webhook is active?

The Bot.run method in bot.go:71-84 enforces mutual exclusion between update modes. If you attempt to start UpdatesViaLongPolling while a webhook receiver is already running (or vice versa), the method returns an error preventing concurrent operation. This design prevents API conflicts and ensures only one mechanism fetches updates at a time.

Which configuration should I use for high-traffic bots processing thousands of updates per minute?

For high-throughput scenarios, increase the channel buffer size using WithLongPollingBuffer(500) or higher to prevent the polling loop from blocking on slow consumers. Keep WithLongPollingUpdateInterval at the default 0s to minimize latency between Telegram and your handler. If your infrastructure experiences transient failures, maintain the default WithLongPollingRetryTimeout(8s) to ensure automatic recovery without manual intervention.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →