Home > Backend Development > Golang > Firestore Client in Google App Engine: Per-Request or Global?

Firestore Client in Google App Engine: Per-Request or Global?

Linda Hamilton
Release: 2024-11-25 11:45:15
Original
530 people have browsed it

Firestore Client in Google App Engine: Per-Request or Global?

Creating a Firestore Client in Google App Engine: Per Request or Global?

Context Awareness in Google App Engine

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 vs. Global Client

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)
}
Copy after login

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.

New Go 1.11 Runtime

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.

Best Practices for Go 1.11 and Firestore

In the new GAE standard runtime, it's recommended to:

  1. 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())
    }
    Copy after login
  2. 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)
    }
    Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template