Sequelize Database Entity Relation for Postgres SQL- One To One Relation

For one-to-one relation in database schema, it is easy to define the relation in Model Class using Sequelize BelongsTo method. Let us consider a schema given below which has Users and UserProfile models. One user can have one UserProfile, Which is 1-to-1 relation.

Sequelize one-to-one relation
Sequelize one-to-one relation

One-to-One Relation using belongsTo in Sequelize

Users Model

const UserModel = db.define(
    userId: {
      field: 'userId',
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    firstName: {
      field: 'firstName',
      type: sqlOperator.STRING(100),
      require: true
    lastName: {
      field: 'lastName',
      type: sqlOperator.STRING(100),
    email: {
      field: 'email',
      type: sqlOperator.STRING(255),
      defaultValue: null,
      allowNull: true,
      // unique: true,
      validate: {
        isEmail: true
    userName: {
      field: 'userName',
      type: sqlOperator.STRING(255),
      defaultValue: null,
      allowNull: true,
      // unique: true
    phone: {
      field: 'phone',
      type: sqlOperator.STRING(13),
      allowNull: true,
      // unique: true
    photo: {
      field: 'photo',
      type: sqlOperator.STRING(1024),
      defaultValue: null,
      validate: {
        isUrl: true
    tableName: 'users',
    timestamps: true,
    freezeTableName: true,

UserModel.associate = async () => {
  console.log('--- Establishing relations between user and user profile ---');

  const UserProfileModel = require('./UserProfileModel');

  UserModel.belongsTo(UserProfileModel, {
    foreignKey: 'profile',
    targetKey: 'userProfileId'
  }); /** foriengKey and targetKey are both from table */

module.exports = UserModel;

UserProfile Model

const UserProfileModel = db.define(
    userProfileId: {
      field: 'userProfileId',
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4
    address: {
      field: 'address',
      type: sqlOperator.STRING(100),
      require: true
    tableName: 'user_profiles',
    timestamps: true,

UserProfileModel.associate = async () => {
  console.log('--- Establishing relations between user profile ---');

module.exports = UserProfileModel;

While defining one to one relation, relation can be defined in any of the model, either User Model or UserProfile model. It will work fine with any way.

Let us understand foreign key and target key in belongsTo as given above.

foreignKey: ‘profile’, since we are defining relation in Users Model, the user profile id will be added to users table and that is why it become one to one relation. Hence foreignKey here means the column name to be added in Source Table that is Users Model.

targetKey: ‘userProfileId’, here the Source is Users model and since we are defining relation in Users Model, then the target model is UserProfiles model, hence the target key here is the primary key of UserProfile table.

As per sequelize documentation, it says “BelongsTo inserts the association key in the source model”, source model here is Users Model.

Be social and help to stop corona – Corona Relief

COVID-19 has affected almost every people, every sector and every nation. There are millions of people suffering with various problems. It is we who are strong financially, physically and mentally have to help people who are in need and be a corona warriors.

How can I help during COVID-19?

Join SociallyGood a trusted first ever marketplace for social service sector to donate thousands of non-profits who are serving millions of people who got affected by corona virus pandemic. Volunteer and donate through SociallyGood

Volunteer and Donate to trusted non-profits, find campaigns running for covid-19 here

Platform Architecture in Computer Science: Caching and File Storage

One of the important aspect of any platform is performance, to increase the performance to satisfy end users with quick access one can not escape from in memory cache. Database operations are always costly, executing complex queries to meet real time needs will make the entire platform slow. For faster access, in-memory cache is very much needed. People use Radis and Kafka.

Before reading further I recommend reading my previous article on platform architecture

Caching in platform Architecture

Now interesting question is where do Caching service fits in my architecture? How do we represent it in platform architecture and where do we integrate caching?

Typically we should have a cache manager within the app which manages caching and database. For any request first we have to check whether required data is in cache ? if not then only hit Database else return from cache.

In case of data update or new insertions , the cache manager has to take care of updating the cache and then make the updated data available for further read operations.

The updated platform architecture looks as follows now

Platform architecture with caching

Redis or Kafka are well known services for in-memory cache, but both have their own purpose, so we have to decide upon what to use when ?

Read more about Redis

File Server for file storage in platform architecture

I thought of covering this also in the same article as it is a small but very important to consider. Because lot of developers have confusion regarding where to store files ? many people will create a folder in their application server and store all files there itself, which is a very wrong for ay real-time applications.

It is recommended to store files in file servers like Amazon AWS S3 bucket and Google Storage, if its publicly sharable multimedia file like image or video then go for Cloudinary kind of CDN services.

Why not to store files in application server?

  1. Application servers like amazon EC2 or Google App engine are not made for file storage, their purpose is to run your app
  2. Application servers are compute engines where you can install any software whichever you need for you app to run in cloud, where as file servers are just providing the storage to store huge files
  3. File servers have different qualities altogether they can take you files backup, create replica if needed, they are capable to transfer huge data fast enough, they are cheaper than app servers
  4. in case of app servers, for some reason if something goes wrong, u may need to create new server quickly and release your app again, if your all file data is also stored in the same server you may loose it permanently, but file server are more reliable for that matter
  5. This is what amazon claims -> Amazon S3 is designed for 99.999999999% (11 9’s) of data durability because it automatically creates and stores copies of all S3 objects across multiple systems.
  6. File servers also provide other services like securing files through authorised access, encrypt the files
  7. Manage and access control – you can create multiple folders and access each folder for specific service so that other services won’t get access to it
  8. File servers like Amazon S3 provide services like querying on the data stored in files, all such nice features you won’t get it in app servers because they are not meant for it

Donate to Help during this COVID-19 Pandemic

We all know how badly Corona Virus has affected millions of people. Daily wage workers and all other businesses are hit badly. Its time to help those who are in need, there are thousands of Non Profits working for COVID-19 situation.

Sewa USA is running Fund raiser program as Sur Surgam, donate for Sewa USA

Sewa Bharati is asking for donations which they use to support daily wake workers, donate for this

You can help health care heros, they are Corona Warriors who are helping people by keeping their life in risk, Donate for Doctors, nurses during this COVID-19 pandemic

Volunteering Opportunities for COVID-19

COVID-19 pandemic has made our life miserable, almost every country is facing hardship due to corona virus. Corona Warriors like doctors, nurses and many millions of social workers are helping us to save us from Corona.

This is the time where everyone has to serve the society to help people and to stop pandemic. There are several Non-Profits working towards this goal. You can find several volunteering opportunities in a Social Service Marketplace called SociallyGood, a trusted platform for Social Service Sector. Here are some of the volunteering opportunities for COVID-19

Some of the trending campaigns which may help you to serve the society are here

Volunteering Campaigns for COVID-19

People are getting frustrated, depressed and feeling lonely during the lockdown due to COVID-19, there are many ways to help people for mental health support during COVID-19

Click here to work for this cause

Food distribution to Migrant workers during COVID-19 Pandemic

Click here to donate for COVID-19

Platform Architecture in Computer Science: Case Study on Various Platforms

Before reading this article, I strongly recommend reading my previous two articles.

Platform Architecture with Multiple Apps Approach

Platform Architecture with Micro-Service Approach

Despite all of these inputs, I am still saying platform architecture depends upon various needs of the platform, hence there is nothing like one standard way, it will be always evolving. Hence let us look into some of the platform architectures to understand even better

  1. Linked in Architecture – Reference – Click Here

Observe here, a separate replica set for Database ?

  1. Uber Architecture – Reference Click Here
  1. Netflix Architecture – Reference Click Here
  1. Ebay Architecture

Read More on Platform Architecture

Thank You

Platform Architecture In Computer Science – Micro Services Approach

We have seen how to design platform architecture with multiple apps, we understood pros and cons of that approach in my previous article, Read it from below link

Read – Platform Architecture with Multiple Apps

For applications like Amazon, Netflix, Linked in the backend systems deals with billions of requests per second. It is not possible to handle such a huge traffic by having one consumer app or one seller app. The solution to such a huge systems is micro service architecture.

Probably Amazon has mastered in Micro Service Architecture which runs over more than 500 micro services, similarly Netflix has over 500 micro services and their API Gateway handles over 2 billion requests daily – Source

So dividing Amazon kind of apps into multiple micro services may have following services

Amazon Kind Of Platforms Micro Services

  1. User & Identity Management Micro Service
  2. Product Management Micro Service
  3. Order Management Micro Service
  4. Payment Management Micro Service
  5. Delivery Management Micro Service
  6. Data Mining Micro Service
  7. AI Micro Service

The Micro Service Architecture Looks as follows for Amazon Kind of Platforms

Advantage of Micro Service Architecture

Highly Scalable: Systems of this kind are highly scalable, capable to handle billions of requests every day

Heterogenous Technology: Another major advantage is we can develop each micro service using different technology whichever is suitable for it. Example Order Management you can develop using nodejs and MongoDB, however for data mining management, you can use python and MongoDB. For payment management you can use Java with Postgres SQL

Easy to Build and Maintain: Your development team might have spread across the world, it is easy to maintain and build any service any time

Ever Evolving: Every micro service can evolve at any great extent without affecting other systems

After knowing all of these the question arises, is Micro Service architecture is the best? Should Every App has to adopt to it ?

The answer is NO : Architecture of every platform greatly varies depends upon the needs of the platform. Micro Services approach is suitable for highly scalable systems, however for smaller platforms having multiple apps under same platform is suitable.

To understand even better Read Case Studies of Different Platform Architectures

Platform Architecture in Computer Science: where do API Gateway & GraphQL fit

In our previous article we have seen why and how to design the platform as multiple apps running in independent server with their own database.

Read in Previous Article

API Gateway and Need of API Gateway in Platform Architecture

But for any platform the most important Managing the API Calls, what I mean here is there should be something in between clients and various services which will receive incoming requests, invokes various apis and return the appropriate results.

Also any backend platform should keep track of Api calls, rate limiting – it is defining the rate at which consumer can access apis, limit the number of api calls per second per user or per app, throttling – is controlling usage of apis for consumers for a given period of time, securing apis through api keys and user authentication.

in platform architecture API Gateway is like front facing for incoming client requests. Apigee is one very popular api gateway, however it is suitable for enterprise and big applications, for small apps and startups where one can’t afford Apigee, they can go for other API Gateways like Google Cloud End Points but it has very limited features OR Kong API gateway.

Boosting your Client Apps Performance and Stability by Adopting GraphQL

GraphQL is a query language for APIs, it is like giving control to clients/apps to fetch what exactly they want rather than decided by server.

Ask for What you need and Get exactly that 🙂

Send a GraphQL query to your API and get exactly what you want

<code>//GraphQL Query to API
  product: {

//This will be input to your API and you will get only that in //response quickly

  product: {
    name: 'Micro Max G6',
    images: &#91;],
    price: '6599 Rs'

Get Multiple Information in Single Request

GraphQL will make your apps lightning speed which even out perform greatly in slow network speed as well, because GraphQL is powerful and returns multiple information in single request, which apps typically get it from different api calls.

There are multiple bunch of benefits of GraphQL and its worth to consider using GraphQL while architecting your Platform. Well where GraphQL fits in your platform architecture ? See the updated architecture diagram

Continue Reading About Micro-Service Platform Architecture

Platform Architecture in Computer Science: With Multiple Apps Approach

There are many ways to design the platform architecture, however every platform has its own unique requirements. The architecture of every platform can vary totally to meet the needs of respective platform.

There are many case studies to look into platform architecture which I will cover in different article, we can look into linked-in, ebay, Amazon and netflix architectures to get better understanding on Platform architecture.

For now in this article we will understand first approach that Having Multiple Apps with its own independent Database and Backend. For our understanding purpose we will consider designing a platform for an Amazon Kind of Online Shopping Platform

Read Basics of Platform Architecture before further reading

Platform Architecture for Amazon Kind of Online Shopping Platform with Multiple Apps Approach

If you consider Amazon kind of Online Shopping Platform, we first have to identify which are the different huge modules which are candidates for making it as a separate app altogether

  1. Sellers or Vendors who sell the products
    1. Seller is the one who has his shop and sell products in amazon
    2. He should be able to add his products
    3. He should be able to manage discounts, offers for his products
    4. He should be able to dispatch his product
    5. He should be able to manage his revenue/profit and other finance aspects
  2. Buyers
    1. The one who buy products in Amazon
    2. He should be able to manage his Cart
    3. He should be able to manage his delivery addresses
    4. He should be able to do payment using his choice of payment mode
  3. Product Dispatch Management
    1. Tracking the product while dispatching from one place to another
    2. Every city has a collection centers and products has to be managed for timely delivery
  4. Products Delivery Management
    1. Once product is reached the destination city it has to be picked by delivery person
    2. Assign delivery person
    3. Deliver to customer and update the status
    4. receive cash in case is Cash-On-Delivery
  5. Amazon Finance Management
    1. This is kind of Super Admin Functionality
    2. Managing refunds
    3. managing failed transactions
    4. Transferring money to Seller

I listed only few functionalities however there will be many more under each of these main features.

Why Can’t be its one super big Monolithic Application ? Rather than multiple Apps ?

To answer this question we have to think of following important aspects which we covered in our first Article Which are as follows

  1. Scalability : For Amazon Kind of Applications, millions of requests will be coming every second. There are millions of users buying and millions of sellers selling and millions of products listed, millions of transactions happening. It is highly impossible to handle everything in one huge monolithic server, because every server has some upper limits with respect to hardware and capacity, one huge database to scale it to that level we have to divide it into multiple pieces and manage it independently.
  2. Maintainability: It is very hard to maintain one huge monolithic app for such a huge volume.
  3. Resilient: Any major update to particular part of the platform should not affect to other parts of the platform
  4. Development: For amazon kind of huge platforms, they have huge team spread across the world and each teach is enhancing their own module by doing lot of research within their small team. It is not possible to manage development activity effectively if its one huge monolithic app

Now let us see how the Architecture Diagram looks: You can use various apps for designing Architecture Diagram

In the above diagram, each app is one server and it has its own database. There are third party services used commonly across many apps, like

  1. Elastic Search Service : For faster product search, Elastic Database is must for better searching capability.
  2. Cloudinary is another service used for multi media file handling
  3. Authentication service is like firebase, auth0 for user authentication
  4. Many more such services will be used

Advantages of Multi Application Platform Architecture

Scalability: In this architecture the platform is scalable to handle high traffic, because during peak time like Amazon big billion day, more and more people will buy products, the traffic will be too high for Consumer App. So in that case if its independent server by itself, we can increase the capacity of that server alone to handle millions of requests, however other apps may not need so much so at this stage.

Continue Reading : Where API Gateway and GraphQL Fit in Platform Architecture