You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
FCM Batch sending deprecated but no migration path #834
I received an email from Firebase about the deprecation of legacy FCM APIs. Notably, the sendAll() method that employs batch sending has been deprecated, and I saw the Node Admin SDK has a new sendEach() method, but the Java SDK does not provide this method.
How should I approach migrating from the sendAll() method?
Reacted by Ruslan Stelmachenko, Lucas Jeremías Couchot, meor9zcu12, Antoine Kleinpeter, Franklin George, mygreen, toby, vellrya, Johannes "Sepp" Stadler, Alexander Emelin and 5 more
Ditto. I have firebase-admin-9.1.1.jar which only exposes these methods below. I've seen mention that these new methods are in firebase-admin 9.2.0, but that doesn't seem to be available anywhere yet.
But I wonder if it'd be feasible to walk back the decision to discontinue the batch send API, or at least move it into the Blaze plan? For people who want a fast, fire-and-forget delivery system, sendEach does not fit the bill. Both theoretically and in real-world tests, sendAll far outperforms its replacement.
Quick tests with 2000 messages (each to a different topic, but with the same config otherwise) on a few of my own servers. No code changes apart from calling a different function, no retry or delay mechanisms in between, apart from what the library itself defaults to:
sendAll: 5-10ssendEach: 1-5m
The overhead of 2000 HTTP calls instead of just 4 has obvious effects. This only becomes worse as the number of messages, meant to be sent approximately "together", increases.
Reacted by yunus emre, Lucas Jeremías Couchot, Mohammed Abbas Ali, Devin Dahoon Kim, Antoine Kleinpeter, amitkumar43, Franklin George, Nicolas Prugne, Beat, Appala Naidu and 14 more
In the FAQ there is a dedicated topic about sending message to multiple tokens in one request.
Q. Does the HTTP v1 API support sending messages to multiple tokens in one request??
A. No. This feature, called "multicast" in legacy HTTP APIs, is not supported by the HTTP v1 API.
For use cases where end-to-end latency is critical, or where total fanout size is small (fewer than 1 million), Google recommends the HTTP V1 API. The HTTP V1 API over HTTP/2 can achieve up to ~1/3 of total message throughput rate compared to legacy multicast when sending on a single connection.
For use cases where throughput and egress bandwidth are prioritized or where total fanout size is large (greater than 1 million), Google recommends topic messaging. While topic messaging requires a one-time action to subscribe recipients to a topic, it offers up to a 10,000 QPS per project fanout rate without a maximum limit on topic size.
The question is: does firebase-admin-java use HTTP V1 API over HTTP/2? And, if yes, how to make SDK to use it? Probably, only Async variants of methods will use HTTP/2 multiplexing, right? Checked the code: both async and non-async variants call each request concurrently. The only difference is in handling the result. So, the only question is: does it use HTTP/2 multiplexing or each concurrent HTTP V1 API request creates a TCP connection?
In the FAQ there is a dedicated topic about sending message to multiple tokens in one request.
Q. Does the HTTP v1 API support sending messages to multiple tokens in one request??
A. No. This feature, called "multicast" in legacy HTTP APIs, is not supported by the HTTP v1 API.
For use cases where end-to-end latency is critical, or where total fanout size is small (fewer than 1 million), Google recommends the HTTP V1 API. The HTTP V1 API over HTTP/2 can achieve up to ~1/3 of total message throughput rate compared to legacy multicast when sending on a single connection.
For use cases where throughput and egress bandwidth are prioritized or where total fanout size is large (greater than 1 million), Google recommends topic messaging. While topic messaging requires a one-time action to subscribe recipients to a topic, it offers up to a 10,000 QPS per project fanout rate without a maximum limit on topic size.
The question is: does firebase-admin-java use HTTP V1 API over HTTP/2? And, if yes, how to make SDK to use it? Probably, only Async variants of methods will use HTTP/2 multiplexing, right? Checked the code: both async and non-async variants call each request concurrently. The only difference is in handling the result. So, the only question is: does it use HTTP/2 multiplexing or each concurrent HTTP V1 API request creates a TCP connection?
Hello, i think it creates to many connection instead of using http2.
We faced with the issue at our system. #849
Hi, I encountered the same issue. I plan to migrate fromsendMulticast to sendEachForMulticast, but the performance of sendEachForMulticast is very bad.
In my testing, to send 20,000 tokens
sendMulticast (sendAll API) : 4 seconds
sendEachForMulticast (sendEach API): 40 seconds
sendEach / sendEachForMulticast is useless for me until it is confirmed officially that supports http2 and have to restricted to http2 only. Otherwise high frequency of opening connection may make system crash.
In addition, I can't find any information about google-http-client:1.43.1 that does support http2
Reacted by Adhiraj S. Chauhan, Lucas Jeremías Couchot, Mohammed Abbas Ali, AntQwanlity, Antoine Kleinpeter, Nicolas Prugne, Mohamad Jouni (Luffy Uzumaki) and Nicholas Petersen
However, I believe the Admin SDK should handle this under the hood. Having to manually add an HTTP/2 layer above the SDK is terrible DX. Might as well use OneSignal.
note: java 11 http client is not good for http2 requests, you should create multiple client for same target host in order to send multiple requests, it creates only one connection per host. I experienced the issue :D so I switched to netty-reactor
All of my tries are fast solutions to send http2 requests, can require improvements.
publicFirebaseAppfirebaseApp() throwsIOException {
GoogleCredentialscredential = GoogleCredentials.fromStream(newFileInputStream(credentialsPath));
ThreadFactorynamedThreadFactory = newThreadFactoryBuilder().setNameFormat("Nio-firebase-http-client-%d").build();
ConnectionProviderconnectionProvider = ConnectionProvider.builder("myConnectionPool")
.allocationStrategy(Http2AllocationStrategy.builder()
.maxConnections(8)
.minConnections(4)
.maxConcurrentStreams(100) // google api responds http2 connection with 100 as max concurrent stream header
.build())
.pendingAcquireMaxCount(100_000)
.build();
// EventLoopGroup bossGroup = new NioEventLoopGroup(2, namedThreadFactory);varclient = HttpClient.create(connectionProvider
)
.protocol(HttpProtocol.H2)
// .runOn(bossGroup)
;
FirebaseOptionsoptions =
FirebaseOptions.builder().setCredentials(credential)
.setHttpTransport(newReactorNettyHttpTransport(client))
.build();
returnFirebaseApp.initializeApp(options);
}
This is better, it does not open many sockets, etc. HTTP2 is used. It solves our main problem.
But the fcm library creates a thread for each request, for example sending 6 batch requests with each batch consisting of 500 device tokens. 6*500= 3k threads will be created.
As I know, each thread requires 1 MB memory, this is another problem.
Overriding the httptransport (FirebaseOptions...setHttpTransport) does not solve batch request issues completely. I do not want to change Firebase library, it requires a lot of effort and also I am not sure which approach is best for creating reactive or async library (CompletableFuture, Mono ...), and I do not have enough time, we are waiting for an official solution :D
I was wondering if it makes sense to create a topic, make all your target devices subscribe to it and then send your message to that topic. Would that be an acceptable strategy?
I was wondering if it makes sense to create a topic, make all your target devices subscribe to it and then send your message to that topic. Would that be an acceptable strategy?
It would work only if you want to send the same message to multiple devices. The batch feature can (or rather could) also be used to send different messages in a single http request, and there doesn't seem to be a workaround for that.
I believe that the sendAll(Async) API should either be maintained or replaced with a better performing API.
The method of sending messages to devices subscribed to a topic, as you suggested, does not meet various business requirements. This method can only be used in cases where it is okay to receive the same message, such as sports relay messages. However, most apps send personalized messages, so this method cannot be used to send messages. Also, creating and configuring new topics every time the target changes can be difficult.
In addition, based on the results provided by the testers you mentioned, sendEach is several times slower than sendAll. I'm not sure why someone would want to get rid of sendAll(Async), but an API that provides the same or better performance should be provided.
Lastly, I hope that Firebase-admin will provide support for netty-based HTTP/2.
Thank you
Reacted by Nicolas Prugne, David Merritt, MattyBoy, Jakub Zak, Green and Nicholas Petersen
@emindeniz99 thanks for sharing another alternative way. Have you tried overriding ThreadManager to have your own pool of threads instead of firing up tons of them by sdk itself?
And instead of rewriting DGFirebaseMessaging class, isn't it better to use your own HttpTransport implementation and pass that to firebase app builder?
@bivrantoshakil hello, thank you, I did not know the thread factory option. I think it should have same behavior as virtual thread to optimize the system, it may not be easy. I did not investigate well.
@emindeniz99 thanks for sharing another alternative way. Have you tried overriding ThreadManager to have your own pool of threads instead of firing up tons of them by sdk itself?
And instead of rewriting DGFirebaseMessaging class, isn't it better to use your own HttpTransport implementation and pass that to firebase app builder?
@bivrantoshakil hello, thank you, I did not know the thread factory option. I think it should have same behavior as virtual thread to optimize the system, it may not be easy. I did not investigate well.
Creating your implementation for ThreadManager is very simple and straight forward. You can pass in your own instance of ExecutorService. I tried with JDK 17 without virtual threads and got very good results
@emindeniz99 thanks for sharing another alternative way. Have you tried overriding ThreadManager to have your own pool of threads instead of firing up tons of them by sdk itself?
And instead of rewriting DGFirebaseMessaging class, isn't it better to use your own HttpTransport implementation and pass that to firebase app builder?
@bivrantoshakil hello, thank you, I did not know the thread factory option. I think it should have same behavior as virtual thread to optimize the system, it may not be easy. I did not investigate well.
Creating your implementation for ThreadManager is very simple and straight forward. You can pass in your own instance of ExecutorService. I tried with JDK 17 without virtual threads and got very good results
I could not understand the benefits of the new threads. To limit parallel thread count? Does it slow down the sending notifications? If not, can you share the implementation logic? Thank you
@emindeniz99 thanks for sharing another alternative way. Have you tried overriding ThreadManager to have your own pool of threads instead of firing up tons of them by sdk itself?
And instead of rewriting DGFirebaseMessaging class, isn't it better to use your own HttpTransport implementation and pass that to firebase app builder?
@bivrantoshakil hello, thank you, I did not know the thread factory option. I think it should have same behavior as virtual thread to optimize the system, it may not be easy. I did not investigate well.
Creating your implementation for ThreadManager is very simple and straight forward. You can pass in your own instance of ExecutorService. I tried with JDK 17 without virtual threads and got very good results
I could not understand the benefits of the new threads. To limit parallel thread count? Does it slow down the sending notifications? If not, can you share the implementation logic? Thank you
If you provide your own implementation of ThreadManager class, then you can control the number of threads as per your need. You can also use any of the built in executors in the JDK itself. This is one example in kotlin
`class FCMThreadManager(maxConcurrentThreadCount: Int) : ThreadManager() {
private val apps = mutableSetOf()
private var executorService: ExecutorService = Executors.newFixedThreadPool(maxConcurrentThreadCount, threadFactory)
override fun getExecutor(app: FirebaseApp): ExecutorService {
apps.add(app.name)
return executorService
}
override fun releaseExecutor(app: FirebaseApp, executor: ExecutorService) {
if (apps.remove(app.name) && apps.isEmpty()) {
executorService.shutdownNow()
}
}
override fun getThreadFactory(): ThreadFactory {
return ThreadFactoryBuilder().setNameFormat("fcm-%d").build()
}
}`
But as you're using http client with HTTP 2.0, the thread limitations will not reduce your overall throughput.
I have tried virtual threads by overwriting ThreadManager and built FirebaseApp with it. I can reach 2 million request per minute, however, I got errors saying that "Error writing request body to server", "Remote host terminated the handshake", "Unexpected end of file from server". When I decrease the load by Semaphore, the errors decreases as well. Do you have any idea what causes these errors? Does FCM apply throttling to my IP or should I change my java docker image?
@bivrantoshakil could you please share us how you initialize firebase app? You mentioned you used virtual threads.
I have tried virtual threads by overwriting ThreadManager and built FirebaseApp with it. I can reach 2 million request per minute, however, I got errors saying that "Error writing request body to server", "Remote host terminated the handshake", "Unexpected end of file from server". When I decrease the load by Semaphore, the errors decreases as well. Do you have any idea what causes these errors? Does FCM apply throttling to my IP or should I change my java docker image?
@bivrantoshakil could you please share us how you initialize firebase app? You mentioned you used virtual threads.
Docker image: eclipse-temurin:21.0.3_9-jre-alpine
@sarismet the implementation you did sounds right. But I think the RPM limit at Firebase is 600k per minute, not 2M.
Hi,
I have tried virtual threads by overwriting ThreadManager and built FirebaseApp with it. I can reach 2 million request per minute, however, I got errors saying that "Error writing request body to server", "Remote host terminated the handshake", "Unexpected end of file from server". When I decrease the load by Semaphore, the errors decreases as well. Do you have any idea what causes these errors? Does FCM apply throttling to my IP or should I change my java docker image? @bivrantoshakil could you please share us how you initialize firebase app? You mentioned you used virtual threads.
Docker image: eclipse-temurin:21.0.3_9-jre-alpine
@sarismet the implementation you did sounds right. But I think the RPM limit at Firebase is 600k per minute, not 2M.
@bivrantoshakil Yes, you are right, but, I expect the error code and response to be related to "rate-limit", not UNKNOWN. I will try to read the trace logs of com.google.firebase
I have implemented http2 based sendmulticast with spring webflux webclient in our project.
This class should be on com.google.firebase.messaging package, you can create it own code but package name should match with it in order to access some SendResponse and similar classes (that can be copied but seems ugly in codebase). Our project is java 17 so we can not benefit from virtual threads. By using webclient, the requests do not block threads. 8 webclient thread handle 600k+ rpm on my macbook. We didn't use the code in production yet, it is open to your feedbacks, thanks
you can use sendMulticastV2
todo: retry policy should be added, like fcm library.
@emindeniz99 I've impemented similar way but our 1% total traffic has beenn due to the following issues. Did you come across these issues and How to fix them?
1.
org.springframework.web.reactive.function.client.WebClientRequestException: nested exception is io.netty.handler.timeout.ReadTimeoutException
at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
*__checkpoint ⇢ Request to POST https://fcm.googleapis.com/v1/projects/dummy/messages:send [DefaultWebClient]
Original Stack Trace:
org.springframework.web.reactive.function.client.WebClientRequestException: Connection prematurely closed BEFORE response; nested exception is reactor.netty.http.client.PrematureCloseException: Connection prematurely closed BEFORE response
at org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:141)
While doing the performance testing with above WebClient config, did you see the reactor metrics reactor_netty_eventloop_pending_tasks?
What is the maximum duration that a connection can remain idle without being closed by Firebase servers?
What is the maximum lifespan of a live connection, assuming continuous traffic flow?
Are there any restrictions on the number of accepted connections that a given instance can have on Firebase servers?
@KrishnakanthYachareni Hi,
I transferred the migration process to another team member, he completed the load test etc. But I did not hear the readtimeout exceptions in our tests and production. It can be due to reactor.netty.http.client.HttpClient configs. Can you share your configs? Also, you can implement retry logic for timeouts.
For the PrematureCloseException, if it is 'warn' log, you can ignore. If not, did you limit the max connection count in the http client config. I have encounter with this error when I set the limit very high, the client can not open new connections and can not get any response etc.
While doing the performance testing with above WebClient config, did you see the reactor metrics reactor_netty_eventloop_pending_tasks?
No, we did not see the webclient metrics.
What is the maximum duration that a connection can remain idle without being closed by Firebase servers? What is the maximum lifespan of a live connection, assuming continuous traffic flow? What is the maximum lifespan of a live connection, assuming continuous traffic flow?
It is default value, I don't know
Are there any restrictions on the number of accepted connections that a given instance can have on Firebase servers?
I did not see any limit on the Firebase docs. But on our side, our one server has a limit to opening connections to the server. So we should limit the connection count. One connection can handle 100 parallel request, so you can set the connection count in the Http2AllocationStrategy to your target value.(to send 3k parallel request, 3000/1000= 30 connection is required). :D We allocated double connection in case a connection is dropped. The others can handle the new requests. Via setting min-max count to the same number, we keep the connections warmed up.
ConnectionProviderconnectionProvider = ConnectionProvider.builder("DGFirebaseMessagingPool")
.allocationStrategy(Http2AllocationStrategy.builder()
.maxConnections(120)
.minConnections(120)
.maxConcurrentStreams(100) // google api// responds http2 connection with 100 as max concurrent stream header
.build())
.pendingAcquireMaxCount(100_000)
.maxConnections(120)
.build();
varclient = HttpClient.create(connectionProvider).protocol(HttpProtocol.H2);
client.warmup().block();
this.webClient = WebClient.builder()
.baseUrl(FCM_URL.formatted(getProjectId(firebaseApp, credential)))
.clientConnector(newReactorClientHttpConnector(client))
.build();
@emindeniz99 Thanks for the response. We have DLQ has setup for timedout requests. But we've been observing 1% of 180 million requests are getting failed due to above mentioned errors. Following is the WebClient configuration and replicated into 10 kuberenetes pods in the production. Do you have any suggestions on the configs?
publicWebClientwebClient() {
varconnectionProvider = ConnectionProvider.builder("fcmConnection")
.maxConnections(500) // Max no of connections that the connection pool can maintain at any given time.
.build();
HttpClienthttpClient = getHttpClient(connectionProvider);
httpClient.warmup().block(); // Eager Initialization of Event loop group, host name resolver and native transport libs.returnWebClient.builder()
.clientConnector(newReactorClientHttpConnector(httpClient))
.baseUrl(firebaseCCMConfig.getFcmHttpEndpoint())
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
privateHttpClientgetHttpClient(ConnectionProviderconnectionProvider) {
returnHttpClient.create(connectionProvider)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 45000)
.option(ChannelOption.SO_KEEPALIVE, true)
.responseTimeout(ofSeconds(5))
.keepAlive(true)
.metrics(true, Function.identity())
.protocol(HttpProtocol.H2);
}
Note: The reactor metric reactor_netty_eventloop_pending_tasks is indeciating how many requests are in pending state and just waiting for worker threads to pickup. So I bumped the reactor threads from 4 - 8 threads.
@emindeniz99 Thanks for the response. We have DLQ has setup for timedout requests. But we've been observing 1% of 180 million requests are getting failed due to above mentioned errors. Following is the WebClient configuration and replicated into 10 kuberenetes pods in the production. Do you have any suggestions on the configs?
publicWebClientwebClient() {
varconnectionProvider = ConnectionProvider.builder("fcmConnection")
.maxConnections(500) // Max no of connections that the connection pool can maintain at any given time.
.build();
HttpClienthttpClient = getHttpClient(connectionProvider);
httpClient.warmup().block(); // Eager Initialization of Event loop group, host name resolver and native transport libs.returnWebClient.builder()
.clientConnector(newReactorClientHttpConnector(httpClient))
.baseUrl(firebaseCCMConfig.getFcmHttpEndpoint())
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
privateHttpClientgetHttpClient(ConnectionProviderconnectionProvider) {
returnHttpClient.create(connectionProvider)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 45000)
.option(ChannelOption.SO_KEEPALIVE, true)
.responseTimeout(ofSeconds(5))
.keepAlive(true)
.metrics(true, Function.identity())
.protocol(HttpProtocol.H2);
}
Note: The reactor metric reactor_netty_eventloop_pending_tasks is indeciating how many requests are in pending state and just waiting for worker threads to pickup. So I bumped the reactor threads from 4 - 8 threads.
Can you increase the readtimeout from 5 sec to higher? Probably, google responds your requests slowly. When using the batch api, we saw very high response times. But after the v1 api, I did not look the response times.
Edit: I tried to see average response time of post request on mobile, it seems 800 ms on high throughput. Tomorrow i will try to percentile 95 and 99, but we may not be tracking the response time for each request.
Edit2: Did you investigate/consider the allocationstrategy option that I have shared? Setting the values may help. But I dont hope :) I do not understand/search the difference between maxconn on connection provider and min and max conn on allocation strategy option. I am not sure which one is correct way.
The shutdown date for the old API has been updated. It has been postponed by one month. Additionally, they have provided a form link to request extensions.
Old date: 6/21/2024 (june)
New Date: 7/22/2024 (july)
Also the library generate new thread for each request. For throughput which i have before (10k per minute) now i need rewrite lib to fixed threadpool and multiple okhttp clients (each can send only 100 parallel http2 frames). Your marketing results: +1Gb ram and +0.5 cpu and minus lifetime of any developer with massive unique pushes...
Activity
AndrWeisR commentedon Jun 21, 2023
Ditto. I have firebase-admin-9.1.1.jar which only exposes these methods below. I've seen mention that these new methods are in firebase-admin 9.2.0, but that doesn't seem to be available anywhere yet.
xak2000 commentedon Jun 21, 2023
I see
sendEach*methods are already implemented in themaster.The question is: when 9.2.0 will be released?
adhirajsinghchauhan commentedon Jun 25, 2023
@xak2000 v9.2.0 was released just a day after your comment.
But I wonder if it'd be feasible to walk back the decision to discontinue the batch send API, or at least move it into the Blaze plan? For people who want a fast, fire-and-forget delivery system,
sendEachdoes not fit the bill. Both theoretically and in real-world tests,sendAllfar outperforms its replacement.Quick tests with 2000 messages (each to a different topic, but with the same config otherwise) on a few of my own servers. No code changes apart from calling a different function, no retry or delay mechanisms in between, apart from what the library itself defaults to:
The overhead of 2000 HTTP calls instead of just 4 has obvious effects. This only becomes worse as the number of messages, meant to be sent approximately "together", increases.
xak2000 commentedon Jun 26, 2023
In the FAQ there is a dedicated topic about sending message to multiple tokens in one request.
The question is: does firebase-admin-java use HTTP V1 API over HTTP/2?
And, if yes, how to make SDK to use it? Probably, onlyChecked the code: both async and non-async variants call each request concurrently. The only difference is in handling the result. So, the only question is: does it use HTTP/2 multiplexing or each concurrent HTTP V1 API request creates a TCP connection?Asyncvariants of methods will use HTTP/2 multiplexing, right?emindeniz99 commentedon Aug 6, 2023
Hello, i think it creates to many connection instead of using http2.
We faced with the issue at our system.
#849
LucasJC commentedon Sep 21, 2023
Hey guys! I had the same experience using sendEach from previous comments.
Are there any plans for improving this new alternative?
meor9zcu12 commentedon Sep 26, 2023
Hi, I encountered the same issue. I plan to migrate from
sendMulticasttosendEachForMulticast, but the performance ofsendEachForMulticastis very bad.In my testing, to send 20,000 tokens
sendMulticast (sendAll API) : 4 seconds
sendEachForMulticast (sendEach API): 40 seconds
sendEach/sendEachForMulticastis useless for me until it is confirmed officially that supports http2 and have to restricted to http2 only. Otherwise high frequency of opening connection may make system crash.In addition, I can't find any information about google-http-client:1.43.1 that does support http2
AntQwanlity commentedon Jan 14, 2024
Found this : https://eladnava.com/send-multicast-notifications-using-node-js-http-2-and-the-fcm-http-v1-api/
Refers to this package : https://github.com/eladnava/fcm-v1-http2/tree/main
Might be useful for some.
However, I believe the Admin SDK should handle this under the hood. Having to manually add an HTTP/2 layer above the SDK is terrible DX. Might as well use OneSignal.
emindeniz99 commentedon Jan 14, 2024
The main issue is caused by google-http-client that does not support http2. default transport interface (NetHttpTransport) is JDK1.1 http connection.
I have tried different http transport layers for fcm library such as netty-reactor, java11-httpclient, springwebflux
googleapis/google-http-java-client@main...emindeniz99:google-http-java-client:main
https://github.com/emindeniz99/google-http-java-client
note: java 11 http client is not good for http2 requests, you should create multiple client for same target host in order to send multiple requests, it creates only one connection per host. I experienced the issue :D so I switched to netty-reactor
All of my tries are fast solutions to send http2 requests, can require improvements.
This is better, it does not open many sockets, etc. HTTP2 is used. It solves our main problem.
But the fcm library creates a thread for each request, for example sending 6 batch requests with each batch consisting of 500 device tokens. 6*500= 3k threads will be created.
As I know, each thread requires 1 MB memory, this is another problem.
Overriding the httptransport (FirebaseOptions...setHttpTransport) does not solve batch request issues completely. I do not want to change Firebase library, it requires a lot of effort and also I am not sure which approach is best for creating reactive or async library (CompletableFuture, Mono ...), and I do not have enough time, we are waiting for an official solution :D
#849
sntg-p commentedon Jan 18, 2024
I was wondering if it makes sense to create a topic, make all your target devices subscribe to it and then send your message to that topic. Would that be an acceptable strategy?
sebphil commentedon Jan 22, 2024
It would work only if you want to send the same message to multiple devices. The batch feature can (or rather could) also be used to send different messages in a single http request, and there doesn't seem to be a workaround for that.
stager0909 commentedon Jan 23, 2024
Hello,
I believe that the sendAll(Async) API should either be maintained or replaced with a better performing API.
The method of sending messages to devices subscribed to a topic, as you suggested, does not meet various business requirements. This method can only be used in cases where it is okay to receive the same message, such as sports relay messages. However, most apps send personalized messages, so this method cannot be used to send messages. Also, creating and configuring new topics every time the target changes can be difficult.
In addition, based on the results provided by the testers you mentioned, sendEach is several times slower than sendAll. I'm not sure why someone would want to get rid of sendAll(Async), but an API that provides the same or better performance should be provided.
Lastly, I hope that Firebase-admin will provide support for netty-based HTTP/2.
Thank you
14 remaining items
emindeniz99 commentedon May 22, 2024
@bivrantoshakil hello, thank you, I did not know the thread factory option. I think it should have same behavior as virtual thread to optimize the system, it may not be easy. I did not investigate well.
bivrantoshakil commentedon May 24, 2024
Creating your implementation for ThreadManager is very simple and straight forward. You can pass in your own instance of ExecutorService. I tried with JDK 17 without virtual threads and got very good results
emindeniz99 commentedon May 24, 2024
I could not understand the benefits of the new threads. To limit parallel thread count? Does it slow down the sending notifications? If not, can you share the implementation logic? Thank you
bivrantoshakil commentedon May 27, 2024
If you provide your own implementation of ThreadManager class, then you can control the number of threads as per your need. You can also use any of the built in executors in the JDK itself. This is one example in kotlin
`class FCMThreadManager(maxConcurrentThreadCount: Int) : ThreadManager() {
private val apps = mutableSetOf()
private var executorService: ExecutorService = Executors.newFixedThreadPool(maxConcurrentThreadCount, threadFactory)
}`
But as you're using http client with HTTP 2.0, the thread limitations will not reduce your overall throughput.
sarismet commentedon Jun 10, 2024
Hi,
I have tried virtual threads by overwriting ThreadManager and built FirebaseApp with it. I can reach 2 million request per minute, however, I got errors saying that "Error writing request body to server", "Remote host terminated the handshake", "Unexpected end of file from server". When I decrease the load by Semaphore, the errors decreases as well. Do you have any idea what causes these errors? Does FCM apply throttling to my IP or should I change my java docker image?
@bivrantoshakil could you please share us how you initialize firebase app? You mentioned you used virtual threads.
Docker image: eclipse-temurin:21.0.3_9-jre-alpine
bivrantoshakil commentedon Jun 11, 2024
@sarismet the implementation you did sounds right. But I think the RPM limit at Firebase is 600k per minute, not 2M.
sarismet commentedon Jun 11, 2024
@bivrantoshakil Yes, you are right, but, I expect the error code and response to be related to "rate-limit", not UNKNOWN. I will try to read the trace logs of com.google.firebase
KrishnakanthYachareni commentedon Jun 18, 2024
@emindeniz99 I've impemented similar way but our 1% total traffic has beenn due to the following issues. Did you come across these issues and How to fix them?
1.
reactor_netty_eventloop_pending_tasks?emindeniz99 commentedon Jun 19, 2024
@KrishnakanthYachareni Hi,
I transferred the migration process to another team member, he completed the load test etc. But I did not hear the readtimeout exceptions in our tests and production. It can be due to reactor.netty.http.client.HttpClient configs. Can you share your configs? Also, you can implement retry logic for timeouts.
For the PrematureCloseException, if it is 'warn' log, you can ignore. If not, did you limit the max connection count in the http client config. I have encounter with this error when I set the limit very high, the client can not open new connections and can not get any response etc.
No, we did not see the webclient metrics.
It is default value, I don't know
I did not see any limit on the Firebase docs. But on our side, our one server has a limit to opening connections to the server. So we should limit the connection count. One connection can handle 100 parallel request, so you can set the connection count in the Http2AllocationStrategy to your target value.(to send 3k parallel request, 3000/1000= 30 connection is required). :D We allocated double connection in case a connection is dropped. The others can handle the new requests. Via setting min-max count to the same number, we keep the connections warmed up.
KrishnakanthYachareni commentedon Jun 19, 2024
@emindeniz99 Thanks for the response. We have DLQ has setup for timedout requests. But we've been observing 1% of 180 million requests are getting failed due to above mentioned errors. Following is the WebClient configuration and replicated into 10 kuberenetes pods in the production. Do you have any suggestions on the configs?
Note: The reactor metric
reactor_netty_eventloop_pending_tasksis indeciating how many requests are in pending state and just waiting for worker threads to pickup. So I bumped the reactor threads from 4 - 8 threads.emindeniz99 commentedon Jun 19, 2024
Can you increase the readtimeout from 5 sec to higher? Probably, google responds your requests slowly. When using the batch api, we saw very high response times. But after the v1 api, I did not look the response times.
Edit: I tried to see average response time of post request on mobile, it seems 800 ms on high throughput. Tomorrow i will try to percentile 95 and 99, but we may not be tracking the response time for each request.
Edit2: Did you investigate/consider the allocationstrategy option that I have shared? Setting the values may help. But I dont hope :) I do not understand/search the difference between maxconn on connection provider and min and max conn on allocation strategy option. I am not sure which one is correct way.
emindeniz99 commentedon Jun 24, 2024
The shutdown date for the old API has been updated. It has been postponed by one month. Additionally, they have provided a form link to request extensions.
Old date: 6/21/2024 (june)
New Date: 7/22/2024 (july)
New Announcement:

Source: https://firebase.google.com/support/faq#deprecated-api-shutdown
jonathanedey commentedon Oct 9, 2024
HTTP/2 support has now been added with the release of v9.4.0.
See our wiki for more information on this change.
The deprecated APIs will also be removed in our next major release. For more information refer to: https://firebase.google.com/support/faq#fcm-23-deprecation
good-vi commentedon Oct 9, 2024
It's joke. I need send 400k UNIQUE pushes (topics can't solve that). Your http2 allow maximum 100 pushes in time for once http client:
Also the library generate new thread for each request. For throughput which i have before (10k per minute) now i need rewrite lib to fixed threadpool and multiple okhttp clients (each can send only 100 parallel http2 frames). Your marketing results: +1Gb ram and +0.5 cpu and minus lifetime of any developer with massive unique pushes...