React Native Database – Choosing the right database for your React Native app
With React Native being looked up as an ideal choice of developing applications, most of the organizations and developers are relying on the framework to ship high-performant native apps. There is a huge pressure on a React Native developer to deliver offline-first and high performing application that can be scaled whenever needed. Thus, it’s often challenging for developer to choose the right technology stack including the appropriate database for React Native. In this article, we have handpicked everything you need to know in order to select the right database for React Native.
Local React Native Database options
We will first start with local databases. The local data storage options for React Native are listed below (Click on the text to know more about the database:
Realm Database for React Native
Realm database was built from scratch for offline and real-time applications running on mobile and wearable devices. Realm is not an ORM or built on top of SQLite, it has its own database engine and doesn’t just rely on key-value stores.
That explains why developers prefer to use Realm while handling a large amount of data or for high-performance applications. Realm allows developers to undergo frequently mapping classes, tables, foreign keys or the fields.
Realm is an object-oriented database rather than a relational database. OO model makes it 10x faster than SQLite and saves you from running tons of query which is a common thing for a typical SQL database.
Benefits of Realm database
Listed below are some of the best benefits of Realm:
- Realm sync – Realm synchronization services run in the background to record and save the user interaction, and service requests locally. Once the device is online, it sends data back to the server and executes the tasks without hindering the user experience.
- Offline-friendly with Redux offline – If you are looking for an alternative solution to implement an offline-first architecture with realm for React native apps – then redux offline might give you a sigh of relief. Redux offline fulfils almost every arbitrary requirements of offline-based architecture
- Security – Realm uses different encryption standards for each mobile platform.
For Android, they use AES-256 level of encryption and decryption of all the data stored locally.Whereas for iOS applications, their encryption is based on the iOS CommonCrypto library, which protects the app data and passwords stored in the keychain. For windows applications, Realm uses Crypto library for encryption. Each of these libraries can be used to generate a 64-byte of encryption keys, where each 4kb block of data is further encrypted with AES-246 Cipher Block Chaining(CBC) method and then signed with an SHA-2 HMAC.
Performance of Realm
In terms of performance, Realm databases have been proven to run queries and sync objects significantly faster than SQLite and others. The objects stored in Realm can be accessed concurrently from multiple threads or sources, and it doesn’t require any specific lock configuration.
The high performance of Realm can be better explained by:
- Built-in storage engine written in C: Reduces dependencies and improves query performance
- Object-based database: The traditional SQLite with ORM abstraction is leaky because ORM simply converts Objects and their methods into SQL statements. Realm, on the other hand, is an object database, meaning your objects directly reflect your database and it doesn’t convert the objects while doing read/write operations.
- Zero-copy: The traditional way of reading data from a database leads to unnecessary copying into language level objects. Realm avoids this by mapping the whole data in-memory, using B+ trees and whenever data is queried, Realm simply calculates the offset, reads from the memory mapped region and returns the raw value.
- Concurrency Control: Realm smoothly handles the concurrency using the MVCC model, which means that multiple read transactions can be done at the same time and reads can also be done while a write transaction is being committed.
Industry Compliances and Realm
While there is no official documentation on the Industrial compliances and Realm compatibility, but their encryption technology has been used by many banks in their consumer-facing applications.
For SOX and GLBA compliances, Realm has been considered secure enough to use.
Realm Database is 100% open source and free. Realm costs $1750 – for the pro version, there’s a commercial version available for free as well.
But, when you buy their platform to build React Native applications, then it will cost you $1750 per month. They also have an edition which comes with Realm Studio, and tons of other development features for Enterprises.
[Update] Brian, VP of Engineering – Realm pointed the following when it comes to RealM
Real time sync in with Realm and React native
When it comes to real time synchronization – that’s what Realm’s platform was built for – demo of Draw app demonstrates this very well. Look at the image below that shows multiple users simultaneously drawing on the shared canvas.
Firebase for React Native
Firebase supports a real-time NoSQL database for react-native. It can be your best bet when it comes to changes like data synchronization and offline data modification. Firebase is pretty much capable of fulfilling the requirements of “M[model] and C[controller] in MVC” to react Native based applications.
Since the idea behind the development of React was to provide a user interface, there was something needed to support and made it fully functional at the backend. This is where firebase as a NoSQL BaaS comes into play.
Benefits of Firebase
Listed below are some of the well-known advantages of Firebase:
- Real-time data Sync – The biggest advantage of using firebase for react-native is that real-time data is synced across all clients at a time. This is really important in the case when your app suddenly goes offline due to unavailability of an internet connection.
- Minimal setup – Another advantage of using react native and firebase together is that it provides a cross-platform API that requires a minimal setup while you are using it with your app. Moreover, you will not need any application server to access data as firebase real-time database can be directly accessed from a mobile device.
- Offline-persistence – Firebase give developers liberty to build real-time applications with additional offline persistent capabilities. This includes marking an user presence as offline/online and storing a timestamp when a user gets disconnected with network every time.
Security with Firebase
Firebase boasts of an easily understandable data access security rule pattern. It is hosted on SSL (Secure Socket Layer) which keeps the connection safe with the client.
However, data is not encrypted at server side which makes it prone to security threats and theft. Hence, it is advisable to not use Firebase as a database for apps which needs to handle sensitive data.
You can use other local databases such as Realm or combination with any other server-side database to store your sensitive data with encryption. However, if you somehow wish to use the same for these apps you need to make sure your data remains encrypted and also your encrypted key doesn’t remain in that database itself.
React Native performance with Firebase
Firebase is good to go with scalable applications where you want to transfer your data to different users at a time without having to care for any data breakage. In fact, data serving and synchronization is extremely fast so that you can easily transfer files to any number of users across the globe.
Moreover, with Firebase, hosting comes an add-on advantage for you. It has free CDN and SSL layer with cloud storage. This is the only area in which firebase triumphed over other local databases.
Industry Compliances and Firebase
Firebase believed to only be compatible with SOX regulations for Financial and Banking organizations.
Firebase is free upto 1GB data storage. However, it also offers a minimal price of $ 25 for 2.5 GB data storage and a pay-as-you go package. Here’s an image showing firebase pricing:
SQLite as local database for React Native
SQLite was designed to provide local storage to mobile apps. It is a relational database management system designed to meet the storage demands of mobile applications. The word “lite” in SQLite describes it as being a lightweight(ed) library based database which requires minimal setup. SQLite can be integrated with the mobile application to directly access the database.
Benefits of SQLite for React Native
Given below are some of the benefits of SQLite:
- ACID-compliant – SQLite can be described as an ACID compliant database that implements most of SQL based standards although with some significant omissions. The architecture of SQLite is file-based with some tools which can handle all types of data with ease and simplicity.
- Offline persistence – To enable offline persistence with SQLite, you can use a react-native-SQLite-storage plugin to manage the data within the app. When a file is generated when you need to instruct from SQLite to open the file that is saved in the documents folder. You can do this by modifying your openDatabase call mentioned in step 6 of this link.
Security with SQLite
SQLite does support data encryption with an extension named as SQLite Encryption Extension (SEE) which is provided on their official website. However, the extension is licensed which means you have to pay the one-time fee to use it.
The extension SEE allows SQLite to read/ write data in an encrypted manner such that data remains inaccessible to outsiders. SEE is built with various algorithms that implement encryption and makes it work for it.
Encryption algorithms such as RC4 with security enhancements, AES-128 in OFB mode, AES-128 in CCM mode and AES-256 in OFB mode are used respectively for each of the seven variants. However, the seventh variant supports all algorithms.
Apart from SEE, there are several others implementations with which you can encrypt your data in SQLite :
- WxSQLite – wxSQLite is a C++ wrapper which can be used to encrypt SQLite data.
- SQLCipher – SQLCipher is an open source extension that supports 256 bits AES encryption. It uses OpenSSL’s libcrypto to implement encryption.
- SQLiteCrypt – It supports API based encryption. It requires custom implementation though.
App performance with SQLite
Often, query performance with SQLite is a matter of discussion among developers. There is a common notion among every developer that SQLite is not better in terms of query performance and speed. However, it is not so. SQLite can be used to query perform at an extreme level.
One of the easiest ways to optimize performance in SQLite is to make the disk access less often. But, to make it happen you must be familiar with the overall understanding of SQLite information processing. You must determine and measure the process where SQLite is consuming more time.
Moreover, while performing basic operations such as insert/ update/ delete in SQLite, you can use the correct set of Begin and End operators so that every time when a transaction initiates, a single DML code gets executed and ends after the completion of modifications.
This approach is simpler and more convenient to use while query performing any SQLite transaction.
Another approach to increasing performance in case of SQLite can be to configure several parameters of DBMS using PRAGMA.
SQLite Database Pricing
SQLite is in public domain, open source and free to use. But, if your organization wants to obtain a license for copyright infringement, then they can pay a one time fee of $6000.
PouchDB based on CouchDB for React Native
PouchDB was built using CouchDB protocols and storage mechanism, and that’s why CouchDB is the most reliable server-side database to pair with PouchDB. Apart from CouchDB, PouchDB is also compatible with MongoDB, MySQL, and PostgreSQL server-side databases.
PouchDB, a DB that Sync with multiple platforms easily
Similar to Firebase, PouchDB data can also be synchronized between multiple users, so there’s no issue of data conflict. Although, If you’re using any native library, then OS specific data can’t be synced between multiple clients.
Peer to Peer Replication in a single stroke
PouchDB with its replication feature allows local storage to be disconnected from the server side while both copies can be updated concurrently. Once it’s updated, the data gets synced across multiple clients without any data leakage.
A really good example of handling such operations efficiently on React native using pouchDB is Evernote. Evernote does that perfectly by letting users update their notes and syncing it back to the main database.
Securing your Local Data in PouchDB
Securing your app’s local data is difficult; but securing your local PouchDB data is relatively easier than most of the open source databases. CouchDB has an inbuilt authentication framework for React Native and it offers some amazing security features:
- Stores the password in the hash form using PBKDF2 cryptography, which is a standard key derivation function to protect encrypted keys from brute force attacks.
- It does stores cookies from the app, but keep refreshing every 10 minutes, which reduces possible attacks on the cookie.
- It supports SSL, so you can easily encrypt your local data with an AES256 level of encryption.
PouchDB best practices for security would be to define proper access control rules, not storing store passwords in memory, and encrypting communications using SSL to make your application will be safe.
PouchDB development and updates are publicly available on Github and it’s free to use.
Async Storage Class for React Native
Async storage is a local storage system, which gives you the ability to store locally and persist the data between app reboots. It comes in-built with React Native, so you can use it without any additional deployment. The downsides are slow to runtime and have no indexing capabilities.
All objects stored in the class named Async Storage are considered as strings, all value must be serialized before storing, and deserialized after retrieving. That explains its slow runtime and no indexing capability. You should not use Async Storage while dealing with a large amount of data.
Read write operations with Async storage
The read/write operations are quite slow compared to any other storage systems. In terms of security, there is no encryption available locally, also the data vanishes if a user deletes the app.
Async Storage doesn’t offer any offline Capability unless you bind it with another full-scale database like SQLite, or Realm.
WatermelonDB for React Native
Built on the top of SQlite, WatermelonDB is a high-performance reactive database for React Native which has the potential to scale hundreds to tens of thousands of records and still remain fast. According to it’s official repository on github, It’s optimized for building complex applications in React Native with maximum focus on real-world performance.
A rule of thumb to use Watermelon is to persist it with slower end devices on which it’s hard to scale for thousands or tens of thousands of database records. Watermelon handles data persistence in slow-end devices by being lazy. Thus, you won’t be loading any requests unless requested at the first place. Here’s the demo of WatermelonDB as a reactive database for React Native: WatermelonDB demo.
Apart from scaling 1000 -10000 records, WatermelonDB supports:
- Fast. Async. Multi-threaded. Highly cached.
- Relational. Built on rock-solid SQLite foundation.
- Static typing with Flow
- Offline-first. Sync with your own backend
Vasern is fast, lightweight and open source data storage for React Native. It’s API is developed not only for local data storage but also for cloud storage and sync across app clients. It is built using Golang – which is a powerful server side language created by Google.
Vern is available for React Native on iOS and Android, which:
- Support languages use UTF-8 encoding.
- Support basic datatypes (string, int, double, datetime, and reference)
- Write schemas. Create, Update, Query and Delete records.
Server/Side Databases for React Native App Development
MongoDB For React Native
MongoDB is an open source, a server-side database that has been built for scalability and complex applications. MongoDB follows a combined approach of using key-value stores and a relational database to store objects in JSON documents with dynamic schemas.
If you’re dealing with a large amount of data, it allows you to modify the schemas without affecting the React Native application runtime.
MongoDB Security and Industry Compliances
MongoDB uses SCRAM-SHA-1 mechanism for authentication and a role-based access control to prevent unauthorized infiltration to server-side data.
To abide with Industry compliances, MongoDB offers Kerberos and LDAP proxies to protect consumer’s data.
With that being said, MongoDB security practices have adhered to these following compliances:
- HIPAA in Healthcare industry
- SOX in Information technology and Banking organizations.
- GLBA(Gramm Leach Bliley Act) for consumer data protection in Financial Corporations.
MongoDB compatibility with React Native
MongoDB as a server-side is compatible with these local databases:
- Async Storage combined with Core Data or SQLite
React Native app performance and scalability with MongoDB
MongoDB was built with scalability and high performance in mind. Organizations like Baidu and Adobe use MongoDB to store and process data from millions of users. According to their official documentation and case studies, the performance can be scaled to:
- 100k+ database read and writes per second without interrupting the standard latency SLAs
- It can store 1 Billion + documents in their database
I believe these metrics would be enough for 95% of the startup and enterprise building their apps with React Native.
MySQL for React Native
MySQL is a relational database that is based on SQL. MySQL is released as an open source license and is developed, distributed and supported by Oracle distributions.
MySQL Performance in React Native applications
MySQL supports thread-based memory allocation which makes it more fast and reliable. Operations such as joins execute faster in MySQL.
Moreover, MySQL does not perform memory allocation after query initialization which is necessary for a better query performance.
MySQL Security in React Native
MySQL is made secure with a password-based encryption system that implements several data layers for security. The verification is host-based which makes it more flexible.
It also supports encryption which makes it more secure from the server-side vulnerabilities.
Scalability and Limits
MySQL is designed to store larger data. There are some cases where it has been easily reported to store about 50 million records. MySQL has the capability to support up to 64 indexes per table.
Each index of the table may incorporate about 1 to 16 columns. Index of InnoDB tables can be wider as either 767 bytes or 3072 bytes whereas MyISAM tables have an index width of about 1000 bytes.
MySQL compatibility with React Native Local Database
If you want to store data locally on the mobile device then you can use AsyncStorage for React Native.
There are few libraries that will allow you to use SQLite with React Native and MySQL. Also, realm works in a great way with MySQL when you are working on Android.
As mentioned above, MySQL can be used to store larger data. So, if you are on a hunt for the server side database which can serve large chunks of data across server, it must be your best bet in that case.
Banking organizations have been using MySQL for their applications, so it’s safe to assume MySQL comply with Banking regulations.
Amazon DynamoDB For React Native
Amazon DynamoDB was designed and developed as a fully-fledged and managed NoSQL database service which runs on the AWS cloud.
DynamoDB is made completely decentralized with minimal administration needs. It is cost effective database with horizontal scaling, so you need to only pay for the storage and your IO throughput while using DynamoDB.
Performance in DynamoDB
DynamoDB is performance optimized as it automatically made the data transfer on tables easier over multiple tables.
While using DynamoDB, you don’t need to take care of scaling and operating of a distributed database. Moreover, complex functionalities of a distributed database such as initial setup, configuration, cluster scaling, replication etc. are managed by Amazon.
You only need to use the API provided, else rest is taken care of.
Security in DynamoDB
With DynamoDB, encryption is easier. When it comes to server-side encryption, data is transferred by the user in an unencrypted form on the server where it will be then encrypted after uploading. Amazon KMS can be used to manage keys.
DynamoDB compatibility with React Native and other Local Databases
For react native, you can use react-native-DynamoDB wrapper by npm. Also, on Github, AWS SDK for React Native Developer preview includes support for S3, DynamoDB, Lambda, and SNS. This starter automatically provisions a Serverless infrastructure with authentication, authorization, image storage, API access, and database operations. It also includes user registration and MFA support.
DynamoDB with Realm: If your app requires running complex queries from the client end then Realm can be your best choice. Moreover, in such case, you can handle the backend purpose with DynamoDB.
When you look at a suitable database for your react native application, you need to know about your requirements in the first place. Realm as local database works well in every possible requirement where SQLite and Core Data fail to the same level of performance, security, and scalability. Firebase is well suited in situations where you want to develop real-time applications. But, if It’s a million dollar idea, then you should better choose Realm or SQLite. SQLite is suitable in such cases where you don’t need to access “real” database but still, you want the capabilities and power of a relational database.
In the case of Server-Side databases
Organizations with a small database and looking for a more generic solution often choose MySQL and other full-scale databases. MySQL lacks speed and developers face difficulties with large volume data and their undefined schemas. MySQL is widely used for its performance, flexibility, reliable data protection and high availability case.
But, when your data is unstructured and complex or when you can’t accurately define your schemas, MongoDB would be the better choice. MongoDB will meet all your challenges with their document-based data modeling.
Opting out for DynamoDB might be a tedious task in terms of scalability. Though DynamoDB can be used at a lower scale it’s often a matter of challenge with a large amount of data.
However, if you are looking for a backend based database to store JSON documents, DynamoDB might be useful in this case.