Home > Article > Backend Development > Firestore Client in Google App Engine: Per-Request or Global?
Google App Engine (GAE) suggests using a context.Context scoped to the HTTP request for each client library. This ensures that the client is tied to the specific request, providing context-specific data for the database operations.
Per-Request Approach:
In the provided example, a new Firestore client is created within the handler function for each request:
func (s *server) person(ctx context.Context, id int) { _, err := s.db.Client.Collection("people").Doc(uid).Set(ctx, p) }
While this approach ensures the client is isolated to the current request, it can be inefficient and introduce unnecessary overhead, especially for long-running requests or high-frequency operations.
Global Client Approach:
An alternative approach is to create a single global Firestore client and reuse it for multiple requests. However, this was not feasible in the old Go runtime in GAE.
With the introduction of the Go 1.11 runtime for GAE standard, the context scoping restrictions have been relaxed. This now allows you to use any context you prefer.
In the new GAE standard runtime, it's recommended to:
Initialize the Firestore client in the main() or init() function using the background context:
func init() { var err error client, err = firestore.NewClient(context.Background()) }
In request handlers, use the request context for API calls:
func handleRequest(w http.ResponseWriter, r *http.Request) { doc := client.Collection("cities").Doc("Mountain View") doc.Set(r.Context(), someData) }
By following these best practices, you can take advantage of the efficiency gains provided by reusing a global Firestore client while still maintaining request-specific context in your database operations.
The above is the detailed content of Firestore Client in Google App Engine: Per-Request or Global?. For more information, please follow other related articles on the PHP Chinese website!