Google Firebase for serverless front-end applications

Google Firebase is a PaaS offering for developing web and mobile apps. Amit Jambusaria explains the advantages and walks through a sample app.

Firebase is a PaaS (Platform-as-a-Service) offering from Google used for application development that supports various setups such as iOS, Android, Web, Unity, C++, or REST for everything else. Google Firebase can be used for a gamut of use-cases. Whether you are building a modest mobile app with relatively simple storage needs or an enterprise application with non-trivial scaling, security and high-availability requirements, Firebase handles it well. Firebase provides comprehensive cross-platform modules for building, releasing and monitoring applications.

Serverless Architecture – Firebase services can be accessed directly from any client application (mobile device or web app), eliminating the need for dedicated servers. The upside here comes in the form of significant savings of time and resources. This article explores some of the key Firebase modules that enable quick and efficient development of Serverless Applications. For the purpose of this article, I have created an example Firebase web application, which I will use to demonstrate the usage of the Firebase SDKs. 

Realtime Database vs Cloud Firestore

Google Firebase has two NoSQL cloud-hosted database offerings that you can choose from – Realtime Database and Cloud Firestore. In both the offerings –

  • Data is synchronized in real-time across all connected clients and across all geo-locations through real-time listeners 
  • Client first SDK (no need for dedicated servers)
  • Offline support for mobile and web 
  • Free tier and then pay for what you use

Advantages of Cloud Firestore over Realtime database 

Structured dataCloud Firestore is a document-model DB, i.e. everything is stored as documents that contain key-value pairs. The values could be anything – strings, integers, floats, lists, binary bits, JSON maps, etc.  These documents are, in turn, grouped into collections. 

In most cases, an application needs several collections that contain documents which point to subcollections. These subcollections contain documents that in turn point to other nested subcollections and so on. This structure of organizing data in collections of documents is very performant since it allows for shallow queries, i.e. ability to query for a document without having to fetch all the linked subcollections. 

   

The image below is a Cloud Firestore DB with a users collection with some user documents. Each user document holds a trips collection.

In comparison, Realtime Database is an unstructured giant JSON tree where there are no formal hierarchy structures. If not designed properly, this can result in unnecessary fetching of nested data that may be not needed on the client.  

Better querying – Cloud Firestore also has better querying capabilities than the Realtime Database. Querying across multiple fields is harder to do in the Realtime Database, which usually involves denormalizing your data. With Firestore, querying multiple fields is natively supported without denormalizing your data. 

Built for scaleCloud Firestore is also a better option for applications with high scaling needs. Realtime Database caps at about 200,000 simultaneous client connections, whereas Cloud Firestore will accept up to 1,000,000 concurrent client connections per database. In addition, it has a better SLA of 99.999% uptime in multi-region instances and 99.99% uptime in regional instances vs Realtime Database, which offers 99.95% uptime.

Multi-region supportCloud Firestore supports multi-region locations. Data is replicated and available for use from multiple geo-locations across the world. In comparison, Realtime Database is available in a single region only with extreme low-latency for apps that need to sync their state frequently.

Offline support – Cloud Firestore offers offline support for iOS, Android and web clients, whereas Realtime DB offers offline support for iOS and Android clients only.

Security – In Cloud Firestore rules are non-cascading, and you can combine authorization and validation vs in Realtime DB rules are cascading with separate authorization and validation.

Google Firestore locations

(Source)

These Firebase database offerings are similar to other industry options such as Microsoft Azure Cosmos Database and AWS DynamoDB.

Why you may still want to use Realtime DB 

While Firestore is better in many ways over Realtime DB, there are a few use cases where Realtime DB might be the right option for you –

  • Realtime Database natively supports presence – telling when a user has come online or gone offline. This is also solved in Cloud Firestore, but the solution is not quite as elegant.
  • Based on the pricing models for Firestore and Realtime DB, applications that perform very large numbers of small reads and writes per second per client are better served on Realtime DB.
  • Realtime DB is also marginally better in latency if you have a particular need around low-latency operations (only in NA).

Cloud functions 

While a lot of processing and database CRUD operations can be performed on the frontend, there are some things that should never be done on the client-side. Firebase extends the Serverless paradigm with Cloud Functions which falls under Functions-as-a-Service (FAAS). Cloud functions allow you to perform secure compute operations abstracted from the client app, directly on Google’s cloud infrastructure. They are similar to AWS Lambdas or Azure Functions.

The image below is a cloud function (for this example web application) called generateStats that contains the business logic for my web application. This business logic is compute-heavy and deals with sensitive data which is not suited for the client. Cloud functions come in handy for such use-cases.

Here is the function definition in the codebase.

 

Authentication Firebase Authentication provides the following auth methods: 

  • Email/password
  • Phone
  • OAuth 2
    • Google
    • Facebook
    • Twitter
    • Github
  • Anonymous
  • Custom auth

It leverages industry-standard security protocols such as OAuth 2.0 and OpenID connect, making it easy to connect with custom backends. The fastest and easiest way to add authentication to an app is to use FirebaseUI Auth, a drop-in UI library. FirebaseUI implements complete user flows for all of Firebase Authentication’s supported sign-in methods. 

For my example web application, I have chosen Email/password, Google and Facebook as authentication methods. Here’s what the authentication code looks like with Firebase Auth provider SDKs 

Here is the signup page with Firebase Auth 

Cloud Storage – Most applications have file storage requirements. Firebase provides Cloud Storage SDKs to manage uploads and downloads for user-generated content such as documents, images, audio, video, etc. Cloud Storage is one of the best options for file storage, considering it provides robust operations regardless of network quality, a simple, intuitive authentication model and is built of exponential scaling needs.

Key capabilities of Cloud Storage are as follows – 

  • Cloud Storage integrates seamlessly with Firebase Authentication to provide an easy to use, seamless authentication engine. The SDK provides a declarative security language to control access based on the file name, size, content-type or other metadata
  • Cloud Storage stores the files on Google Cloud Storage bucket which makes it accessible to Firebase SDKs for file upload / download from mobile clients; as well as access to Google Cloud for server-side processing
  • Firebase SDKs for Cloud Storage operations are very robust and can perform I/O operations regardless of network quality. 
  • It is also built for scale with up to an exabyte of storage if your app goes viral.

Here is an example usage of Cloud Storage. 

To incorporate Cloud Storage in web application

  1. Go to Firebase console → Storage dashboard  
  2. Click the Files tab → header of the file viewer.
  3. Copy the URL to your clipboard
  4. To your firebaseConfig object in your app, add the storageBucket attribute with your bucket URL:

Hosting – Static and dynamic content hosting needs can be met with Firebase Hosting. Whether it’s HTML markup, CSS or Microservices in JS, all kinds of content hosting can be deployed to global CDN (represented below). Zero-config SSL and SSD caches and efficient compression techniques ensure that content is delivered swiftly and securely.

(Source)

Advantages of Firebase Hosting

  • Fast delivery of content – Each file (whether HTML, css or js) is cached on SSDs at CDN edges around the globe, served as compressed gzip or Brotli.
  • Built-in secure connections – SSL comes out of the box with Firebase hosting with zero configuration overhead for the application developer. 
  • Preview changes before deployment – Firebase hosting also allows you to view and test your changes on a locally hosted URL and interact with an emulated backend.
  • Faster deploys with one command – With the Firebase CLI, you can get the app deployed and running within seconds. One-click rollbacks are also supported.
  • View changes in an emulator before they go live. You can also set up a temporary preview URL along with GitHub integration for easier CI/CD development.
  • Firebase Hosting can also serve Dynamic content and host microservices (through Cloud Run) as well as Cloud Functions. All content served over HTTPS.

Hosting has a maximum limit of 2Gb for individual files, and Storage is free up to 10Gb. Larger files should be stored on Google Cloud Storage where the individual file limit is up to a terabyte. To control your usage, you can even set limits for your releases and delete targeted releases.

The image below is the example web application being served from Firebase hosting.

Cloud messaging 

Firebase Cloud messaging (previously known as Google Cloud Messaging) is used for iOS and Android notifications and notifications that show up in the corner of your browser. These notifications are really useful when it comes to improving and retaining user engagement. Cloud Messaging can also be used for IM use-cases, where it can transfer up to 4kb of payload to the client app.

An FCM module consists of two primary components for sending and receiving: Send messages via Cloud Functions or from your own server application; and Receive messages via a service worker on web iOS or Android client app using the platforms transport service. The FCM SDK is only supported over HTTPS due to its use of service workers. The image below is the boilerplate for Cloud Messaging on the example application-

A/B testing – A/B testing refers to an experiment where two or more variants of a page, feature or workflow are served to end-users at random. Statistical analysis is used to determine which variation performs better towards a given objective such as conversion rate, page views or user engagement. Firebase A/B testing module allows you to test your application’s UI and provides a data-driven approach to discover a “winner” between control and one or more variations. It even lets you perform multivariate and multi-page testing towards improving overall KPIs.

Types of A/B tests supported by Firebase

Analytics – Using the Firebase SDK, you can get unlimited reporting for 500 distinct events on Google Analytics, which lets you make informed decisions for your product. This dataset can easily be linked to Google BigQuery, which lets you perform further analysis and provides comprehensive reporting tools via Google Data Studio. There is also an out of the box dashboard on the Firebase console that provides a high-level summary of data points such as active users, demographics, geo-locations, etc.

Google Firebase for Serverless Front-end Applications

I discussed some of the key Firebase modules in this article. The entire Firebase offering is divided into three categories as follows – 

 

  • Build – Get to market and deliver value to your users, faster
    • Authentication
    • Cloud Firestore DB
    • Realtime DB
    • Cloud Storage
    • Hosting
    • Cloud Functions
    • Machine Learning
  • Release and MonitorTo improve app quality in less time with less effort
    • Google Analytics
    • Performance Monitoring
    • Test Lab
    • App Distribution
    • Crashlytics
  • Engage – For optimizing your app experience and keep users happy
    • A/B Testing
    • Cloud Messaging
    • Crashlytics
    • Dynamic Links
    • In-app Messaging
    • Predictions
    • AdMob
    • Remote Config

These products together make for a powerful suite of app dev tools that can significantly improve your speed to market and reduce overall operating costs while enabling critical insights towards improving your customers’ online experiences.