Skip to content

HTTP/2 PROTOCOL_ERROR and TaskCanceledException during FCM requests FCM 请求出现 HTTP/2 PROTOCOL_ERROR 和 TaskCanceledException #591

Open

Description

@Wolffy101

Environment / 环境

  • FirebaseAdmin: Custom build based on 3.0.1 / 基于 3.0.1 的自定义构建
  • Product: FCM
  • OS: Linux (Kubernetes)
  • .NET: 10

Description / 问题描述

Over the past few days, we have frequently observed the following exceptions during FCM requests. Repeated cancellation exceptions are concentrated on one pod. No application cancellation token is passed in the normal send path.

最近几天,FCM 请求频繁出现以下异常,其中取消异常集中在一个 Pod 持续发生。普通发送路径未传入业务取消令牌。

HTTP/2 protocol error / HTTP/2 协议错误

System.Net.Http.HttpRequestException:
The HTTP/2 server sent invalid data on the connection.
HTTP/2 error code 'PROTOCOL_ERROR' (0x1).
 ---> System.Net.Http.HttpProtocolException
 at System.Net.Http.Http2Connection.Http2Stream.ReadResponseHeadersAsync(...)
 at System.Net.Http.Http2Connection.SendAsync(...)
 at Google.Apis.Http.ConfigurableMessageHandler.SendAsync(...)

Cancellation / 取消异常

System.Threading.Tasks.TaskCanceledException:
The operation was canceled.
 at System.Net.Http.Http2Connection.Http2Stream.<>c.<WaitForDataAsync>b__88_0(...)
 at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(...)
 at System.Threading.TimerQueue.FireNextTimers()
--- End of stack trace from previous location ---
 at Google.Apis.Http.ConfigurableMessageHandler.SendAsync(...)
 at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(...)

Stack traces are shortened and sanitized. / 堆栈已精简并脱敏。

HTTP configuration / HTTP 配置

We provide a custom Google.Apis.Http.IHttpClientFactory backed by SocketsHttpHandler:

我们通过自定义 Google.Apis.Http.IHttpClientFactory 使用以下 SocketsHttpHandler 配置:

new SocketsHttpHandler
{
    AllowAutoRedirect = false,
    AutomaticDecompression = decompression,
    EnableMultipleHttp2Connections = true,
    PooledConnectionLifetime = TimeSpan.FromMinutes(5),
};

decompression is either GZip | Deflate or None, depending on the SDK factory options.

decompression 根据 SDK 工厂选项设置为 GZip | Deflate 或 None。

A custom DelegatingHandler sets the version policy and logs exceptions before rethrowing them:

自定义 DelegatingHandler 设置版本策略,并记录异常后重新抛出:

try
{
    request.VersionPolicy = HttpVersionPolicy.RequestVersionOrHigher;
    return await base.SendAsync(request, cancellationToken);
}
catch (Exception ex)
{
    logger.LogWarning(ex, "Firebase HTTP request failed");
    throw;
}

Questions / 希望确认

Could our custom HTTP configuration contribute to these exceptions? Are there recommended configuration changes or fixes?
自定义 HTTP 配置是否可能导致这些异常?是否有推荐的配置调整或修复方案?

What diagnostics should we collect to identify the cancellation source and correlate retry attempts with the final send result?
建议收集哪些诊断信息,以定位取消来源并关联重试与最终发送结果?

If the SDK retries successfully and the final send succeeds, can these inner-handler exceptions be treated as transient and logged at a lower severity? Under what conditions should they require further investigation?
如果 SDK 重试后最终发送成功,是否可以将这些内部 Handler 异常视为瞬时故障并降低日志级别?哪些情况下仍需要进一步排查?

Activity

  1. lahirumaramba commented on Nov 5, 2026

    @lahirumaramba
    Member

    Hi @Wolffy101,

    1. Could our custom HTTP configuration contribute to these exceptions? Are there recommended configuration changes or fixes?

    Yes. By default, SocketsHttpHandler disables HTTP/2 keep-alive pings. If NAT or a firewall silently drops an idle pooled HTTP/2 connection, SocketsHttpHandler keeps sending new streams over that dead connection (up to your 5-minute PooledConnectionLifetime) until requests hit the 100-second HttpClient.Timeout (TaskCanceledException). Stale connections or middlebox resets can also surface as HTTP/2 PROTOCOL_ERROR.

    Enable HTTP/2 keep-alive pings with HttpKeepAlivePingPolicy.Always so idle connections stay warm across NAT and dead connections are evicted before new requests use them, and prefer explicit HTTP/2 with fallback:

    var handler = new SocketsHttpHandler
    {
        AllowAutoRedirect = false,
        AutomaticDecompression = decompression,
        PooledConnectionLifetime = TimeSpan.FromMinutes(5),
        EnableMultipleHttp2Connections = true,
        KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always,
        KeepAlivePingDelay = TimeSpan.FromSeconds(30),
        KeepAlivePingTimeout = TimeSpan.FromSeconds(15),
    };
    
    // In your DelegatingHandler.SendAsync:
    request.Version = HttpVersion.Version20;
    request.VersionPolicy = HttpVersionPolicy.RequestVersionOrLower;

    2. What diagnostics should we collect to identify the cancellation source and correlate retry attempts with the final send result?

    • Correlate retries: The SDK's ConfigurableMessageHandler wraps your DelegatingHandler and reuses the same HttpRequestMessage across up to 5 total tries (initial try + up to 4 retries). Store an attempt counter and start timestamp in request.Options (HttpRequestOptionsKey<T>), or enable SDK logs via Google.ApplicationContext.RegisterLogger(...).
    • Confirm timeout source: HttpClient links its 100s timeout token outside the SDK retry loop, so cancellationToken.IsCancellationRequested inside DelegatingHandler will be true even on an HttpClient.Timeout, and that 100s budget spans all retries. Check whether total elapsed time from Attempt 1 is ~100s (when your caller passed CancellationToken.None), or check ex.InnerException is TimeoutException at the outer SendAsync call site.
    • Spot bad connections: Log the pod name and (ex.InnerException as HttpProtocolException)?.ErrorCode to see if failures cluster on one pod.

    3. If the SDK retries successfully and the final send succeeds, can these inner-handler exceptions be treated as transient and logged at a lower severity? Under what conditions should they require further investigation?

    • HttpRequestException (including HTTP/2 PROTOCOL_ERROR): Yes, on intermediate attempts. The SDK automatically retries HttpRequestException and evicts broken HTTP/2 connections from the pool. Using your request.Options attempt counter, you can log attempts 1 to 4 at Debug and attempt 5 (retries exhausted) at Warning or Error (note that SendEachAsync records final failures on BatchResponse.Responses[i].Exception rather than throwing).
    • TaskCanceledException: Keep at Warning or Error. The SDK does not retry TaskCanceledException, so each one in your inner handler is a failed FCM send.
    • When to investigate further: When all 5 attempts fail, when TaskCanceledException continues after enabling KeepAlivePingPolicy.Always, or when errors stay concentrated on a specific pod or node.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions