ReactNative – iOS Xcode 14 + MacOS X Ventura – build errors Duplicate Symbols for Architecture arm64

Building ReactNative Apps is always little hard when there is an Operating System Update along with that Xcode updated. Every time when Xcode is updated to a newer version, Apple make some changes which will start affecting iOS app build in ReactNative.

ReactNative iOS App build errors with Xcode 14 and Mac OS X Ventura

Recently when I updated Mac OS X Ventura, It also forced me to update Xcode to latest version 14. After Xcode update, my ReactNative App started failing with lots of errors. I have ReactNative app which is using RN version v0.59.9, Xcode started throwing linking errors like

42 Duplicate symbols for architecture arm64

the complete error looks as follows

duplicate symbol '_OBJC_CLASS_$_FBSDKBase64' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKBase64.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKBase64.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKBase64' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKBase64.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKBase64.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKBasicUtility' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKBasicUtility.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKBasicUtility.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKBasicUtility' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKBasicUtility.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKBasicUtility.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKCrashHandler' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKCrashHandler.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKCrashHandler.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKCrashHandler' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKCrashHandler.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKCrashHandler.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKLibAnalyzer' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKLibAnalyzer.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKLibAnalyzer.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKLibAnalyzer' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKLibAnalyzer.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKLibAnalyzer.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKTypeUtility' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKTypeUtility.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKTypeUtility.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKTypeUtility' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKTypeUtility.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKTypeUtility.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSession._session' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSession.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSession.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKURLSession' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSession.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSession.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKURLSession' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSession.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSession.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSession._delegateQueue' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSession.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSession.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSession._delegate' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSession.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSession.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSessionTask._handler' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSessionTask._loggerSerialNumber' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSessionTask._task' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKURLSessionTask' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKURLSessionTask' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSessionTask._requestStartDate' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_OBJC_IVAR_$_FBSDKURLSessionTask._requestStartTime' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKURLSessionTask.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKURLSessionTask.o)
duplicate symbol '_FBSDKAppEventCity' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventCountry' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventGender' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventZip' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventEmail' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventDateOfBirth' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventState' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_OBJC_CLASS_$_FBSDKUserDataStore' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKUserDataStore.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_OBJC_METACLASS_$_FBSDKUserDataStore' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKUserDataStore.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventPhone' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventFirstName' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
duplicate symbol '_FBSDKAppEventLastName' in:
    /Users/xyz/Library/Developer/Xcode/DerivedData/MyProject-bmkdjxadfihkgxdpmjllovjakstn/Build/Products/Release-iphoneos/FBSDKCoreKit/libFBSDKCoreKit.a(FBSDKAppEvents.o)
    /Users/xyz/MyComputer/Development/MyProject/SourceCode/MyBranches/saz_mobile/mobile_rn_dev/sazappmobile/MyProject/ios/Pods/FacebookSDK/FBSDKCoreKit_Basics.framework/FBSDKCoreKit_Basics(FBSDKUserDataStore.o)
ld: 42 duplicate symbols for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

When I started looking for solution, I found multiple solutions, which actually worked for many people, however for me none of those solutions worked.

Solution for Duplicate Symbols for architecture arm64 – which worked for me

Steps to resolve

  1. Open your project in Xcode
  2. Click on Pods project from your project navigator as shown in below diagram
    then select Build Phases and select the project target in which you are getting errors. For me all linking errors were for FBSDKCore, you can find that by seeing the error.

  3. Then from error get the file name for which you are getting duplicate symbol. for example if error has
    duplicate symbol ‘_FBSDKAppEventLastName’ in: /libFBSDKCoreKit.a(FBSDKAppEvents.o)
    Then find file FBSDKAppEvents.m from the search box given in above screenshot.
  4. Find the file and select the file and delete by clicking on delete(-) icon in the Xcode. ( refer below screenshot)
  5. Since in my case there are 42 linking errors, all the errors are coming from more than 4 to 5 different files. I deleted all the files one by one.
  6. This resolved all 42 linking error.

Basically the error appears when same implementation is referenced more than one in the project. Which mean in my case some of the .m files from FBSDKCoreKit are added more than once, it is difficult to find how those files added twice, but usually it happens when libraries are linked through pods as well as manually ( typically in old projects libraries might have also linked using ReactNative link command)

Now question is why Xcode 14 started giving errors? which was not the case earlier with lower version of Xcodes ? this is basically because the latest Xcode checks strictly many things and it starts complaining.

Is it the only solution which fix this issue ? well that I am not sure, there are many more solutions giving in StackOverflow as well as GitHub, some fixes might work for you. Here are those references for you, in case my fix doesn’t work for you 🙂

References:

1. Github Post- duplicate symbols for architecture x86_64 React Ntaive version 0.64 #32016

2. Github Post – duplicate symbols for architecture x86_64 React Ntaive

3. Stack over flow post – Duplicate Symbols for Architecture arm64

Resolving Duplicate class error in React Native Android while integrating Native Modules

What is a Duplicate Class issue?

React native has evolved so much that you will really get helpful docs on external packages for most of the things. But there are some corner cases for which we do not find the npm modules to integrate. In those cases, we have to integrate SDK/package in the native side and then write a bridging code in order to call it from React-Native JS code.
  As your project grows and as you start integrating the new SDKs you will somewhere end up with this issue, “Duplicate class” in android. Basically, this issue says this module is already included in one of the SDK and the new SDK we are including also has the same modules and same classes and its a run time java error
  I was so panicked about this issue since I had got a big list of duplicate class issues as you see in the below image and error text below.

Java.lang.RuntimeException: Duplicate class 

com.google.android.gms.dynamite.descriptors.com.google.android.gms.vision.dynamite.face.ModuleDescriptor found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzca found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar 

(com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzcb found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)

  Duplicate class com.google.android.gms.internal.vision.zzcc found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzcd found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzce found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzci found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzcj found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzck found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar 

(com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzcl found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzcm found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.internal.vision.zzl found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-20.1.3-runtime.jar (com.google.android.gms:play-services-vision:20.1.3)


  Duplicate class com.google.android.gms.vision.face.ChimeraNativeBaseFaceDetectorCreator found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.vision.face.FaceDetectorV2Jni found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)


  Duplicate class com.google.android.gms.vision.face.NativeFaceDetectorImpl found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)

Solution for Duplicate Class Error in React Native

Do not worry about the big error message, basically, everything is a single issue but android is making us complicated in presenting. The solution to this issue is very simple but you need to understand the issue properly. Without understanding the issue and just trying with StackOverflow and Github answers it took about a week to fix this.
You will find plenty of the answers in GitHub and StackOverflow for this issue and, they are correct, but they have not elaborated the answer and think that people from the android background can solve this easily. But if you do not know much about the android part then please have a look at this solution.
For integrating a new SDK I got so many duplicate class issues as my project was big and had already many SDKs. In my list of Duplicate class issues, ALl issues are the same but for different modules. I will just one and explain about it.

Duplicate class com.google.android.gms.dynamite.descriptors.com.google.android.gms.vision.dynamite.face.ModuleDescriptor found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar (com.google.firebase:firebase-ml-vision-face-model:17.0.2) and jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)

So error says that there is a duplicate class in these two modules
Module1: com.google.android.gms.dynamite.descriptors.com.google.android.gms.vision.dynamite.face.ModuleDescriptor found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar(com.google.firebase:firebase-ml-vision-face-model:17.0.2)
Module 2:
jetified-play-services-vision-face-contour-internal-16.1.0-runtime.jar (com.google.android.gms:play-services-vision-face-contour-internal:16.1.0)

https://github.com/react-native-camera/react-native-camera/issues/3031#issuecomment-732135774

https://stackoverflow.com/questions/58808875/how-to-resolve-duplicate-class-exception-caused-by-com-google-firebasefirebase

As per the answers I found from Github, We need the exclude one of the groups and module from one of the modules and remember not both of them.

implementation platform('com.google.firebase:firebase-bom:26.1.0'){
exclude group: 'com.google.android.gms'
}

The hardest part for me with an issue I found was identifying which one is a module and which one is a group. That’s why it took me a week to find the solution. If you know which one is module and group then it just works with one shot.
Now we know that out of two modules we need to exclude only one module and not both. Considering the first module out of two.
com.google.android.gms.dynamite.descriptors.com.google.android.gms.vision.dynamite.face.ModuleDescriptor found in modules jetified-firebase-ml-vision-face-model-17.0.2-runtime.jar(com.google.firebase:firebase-ml-vision-face-model:17.0.2)
In this part we need to identify module and the group to exclude,
Now consider only this part com.google.firebase:firebase-ml-vision-face-model:17.0.2
Module: com.google.firebase
Group: firebase-ml-vision-face-model

The rest of the description and version numbers and all just ignore it.
Now go to your android app/build.gradle and exclude this module configuration

That’s it. Re-run your project and you will find this issue anymore

Posted by:
Anand S,
Software Engineer, NIUM India Pvt Ltd

NodeJs createProxyServer Error: connect ECONNREFUSED 127.0.0.1

There is a serious a very random issue with NodeJs with ExpressJS and ‘http-proxy’. There is no proper sequence for this exception, it may come, may not come. For some people the issue is coming consistently, for some people issue is coming randomly.

Interesting observation is, this issue is appearing most of the time when we host the app in cloud platforms like Google GCP, Amazon AWS or Heroku. However we still have no proper answer for this, though the same question is asked multiple times in different Stack Over Flow Posts and other forums. below is the code which is causing the issue

const express = require('express');
const path = require('path');
const logger = require('morgan');
const http = require('http');
//PROXY
const httpProxy = require('http-proxy');
const app = express();
app.use(express.static(path.join(__dirname, '../../../../build')));
app.use(express.static(path.join(__dirname, 'public')));
const apiProxy = httpProxy.createProxyServer();
app.use('/api', (req, res) => {
  console.log('---- api called ----');
  apiProxy.web(req, res, { target: `http://localhost:${process.env.API_PORT}` });
});


  function normalizePort(val) {
    const port = parseInt(val, 10);

    if (isNaN(port)) {
      // named pipe
      return val;
    }

    if (port >= 0) {
      // port number
      return port;
    }

    return false;
  }
  
  /**
   * Get port from environment and store in Express.
   */
  const port = normalizePort(process.env.PORT || 8080);
  console.log('--- client port --- ', port);
  app.set('port', port);

  // app.get('*.js', function (req, res, next) {
  //   console.log('---- ** returning gz');
  //   req.url = req.url + '.gz';
  //   res.set('Content-Encoding', 'gzip');
  //   next();
  // });

  /**
   * Create HTTP server.
   */

  const server = http.createServer(app);

  /**
   * Event listener for HTTP server "error" event.
   */

  function onError(error) {
    if (error.syscall !== 'listen') {
      throw error;
    }

    const bind = typeof port === 'string'
      ? 'Pipe ' + port
      : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  }

  /**
   * Event listener for HTTP server "listening" event.
   */

  function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  }
  /**
   * Listen on provided port, on all network interfaces.
   */

  server.listen(port);
  server.on('error', onError);
  server.on('listening', onListening);

Exception Occurred is Error: connect ECONNREFUSED 127.0.0.1:4001

complete error printed in console is as follows

A 2021-01-27T09:44:46Z npm ERR!     /root/.npm/_logs/2021-01-27T09_44_46_065Z-debug.log
 
A 2021-01-27T09:44:46Z npm ERR! A complete log of this run can be found in:
 
A 2021-01-27T09:44:46Z 
 
A 2021-01-27T09:44:46Z npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
 
npm ERR! Failed at the [email protected] start script.
 
npm ERR! 
 
npm ERR! Exit status 1
 
npm ERR! [email protected] start: `node src/server/apiServer & node bin/www`
 
npm ERR! errno 1
 
npm ERR! code ELIFECYCLE
 
Error: connect ECONNREFUSED 127.0.0.1:4001
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
 
  undefined

React-16 + Material-UI v4.10.X CSS not loading issue in Server Side Rendering

Server side rendering in React 16 is always a tricky, it behaves different than client side rendering. One of the typical issue we face for SSR apps is CSS not loading and images are not rendering.

Interesting observations are CSS are being rendered properly in landing page, however in any other routes CSS are missing. This issue is very obvious when we are using Material-ui library. In every new release Material-UI is making drastic changes and hence its being little tough to upgrade library.

The complete Code for Server Side Rendering in React16 and Material-UI is here

For CSS not loading in SSR app another mistake could be not referring to your build folder in server side code, hence kindly first check below article to make necessary changes which is mandatory.

CSS & Images not loading in React SSR App

However to support Material-UI v4.10.x we need to change two files in the code given in above link. We have to change request handler and App.js “<Provider> part”

Here is the updated code given below

requestHandler.js File Changes

'use strict';

import React from 'react';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { applyMiddleware, createStore } from 'redux';
import { renderToString } from 'react-dom/server';
import { ServerStyleSheets, ThemeProvider, createMuiTheme } from '@material-ui/core/styles';

// import JssProvider from 'react-jss/lib/JssProvider';
import path from 'path'
import fs from 'fs'
// import {
//   MuiThemeProvider,
//   createMuiTheme,
//   createGenerateClassName,
// } from '@material-ui/core/styles';
import green from '@material-ui/core/colors/green';
import red from '@material-ui/core/colors/red';
import { StaticRouter, matchPath } from 'react-router-dom';
import DocumentMeta from 'react-document-meta';
import reducers from '../Reducers';
import routes from '../Routes';
import routesConfigs from './routesConfig';

const middleware = applyMiddleware(thunk);

// const escapeRegex = /([[\].#*$><+~=|^:(),"'`\s])/g;
// let classCounter = 0;

// export const generateClassName = (rule, styleSheet) => {
//   classCounter += 1;

//   if (process.env.NODE_ENV === 'production') {
//     return `c${classCounter}`;
//   }

//   if (styleSheet && styleSheet.options.classNamePrefix) {
//     let prefix = styleSheet.options.classNamePrefix;
//     // Sanitize the string as will be used to prefix the generated class name.
//     prefix = prefix.replace(escapeRegex, '-');

//     if (prefix.match(/^Mui/)) {
//       return `${prefix}-${rule.key}`;
//     }

//     return `${prefix}-${rule.key}-${classCounter}`;
//   }

//   return `${rule.key}-${classCounter}`;
// };

function renderView(req, res, state) {
  const sheets = new ServerStyleSheets();
  // Create a theme instance.
  const theme = createMuiTheme({
    palette: {
      primary: green,
      accent: red,
      type: 'light',
    },
  });

  // STEP-1 CREATE A REDUX STORE ON THE SERVER
  const store = createStore(reducers, state, middleware);
  // const sheetsRegistry = new SheetsRegistry();
  // Create a sheetsManager instance.
  // const sheetsManager = new Map();
  //commented below and using the function pasted above to solve css problem in sidebar and for buttons component
  // const generateClassName = createGenerateClassName();
  // STEP-2 GET INITIAL STATE FROM THE STORE

  const initialState = JSON.stringify(store.getState()).replace(/<\/script/g, '<\\/script').replace(/<!--/g, '<\\!--');
  // STEP-3 IMPLEMENT REACT-ROUTER ON THE SERVER TO INTERCEPT CLIENT REQUESTs AND DEFINE WHAT TO DO WITH THEM
  const context = {};
  
  const reactComponent = renderToString(
    sheets.collect(
    // <JssProvider generateClassName={generateClassName}>
      <ThemeProvider theme={theme}>
        <Provider store={store}>
          <StaticRouter
            location={req.url}
            context={context}>
            {routes}
          </StaticRouter>
        </Provider>
      </ThemeProvider>
      ),
    // </JssProvider>
  );
  // const css = sheetsRegistry.toString()
  const css = sheets.toString();
  const reactMetaComponent = DocumentMeta.renderToStaticMarkup();
  if (context.url) {
    // can use the `context.status` that
    // we added in RedirectWithStatus
    redirect(context.status, context.url);
  } else {
    //https://crypt.codemancers.com/posts/2016-09-16-react-server-side-rendering/
    //res.status(200).render('index', { reactComponent, reactMetaComponent, initialState });
    fs.readFile(path.resolve('build/index.html'), 'utf8', (err, data) => {
      if (err) {
        return res.status(500).send('An error occurred')
      }
      const replacedData = data.replace(
        '<div id="root"></div>',
        `<div id="root">${reactComponent}</div>
        <style id="jss-server-side">${css}</style>
        <script>
          window.INITIAL_STATE = ${initialState}
        </script>`
      );
      const replacedMetaTagData = replacedData
        .replace(`<meta id="reactMetaTags"/>`,
          `${reactMetaComponent}`);
      res.send(replacedMetaTagData);
    })
  }
}

function handleRender(req, res) {
  // filter matching paths
  // and check if components have data requirement
  const components =
    routesConfigs.filter(route => matchPath(req.path, route))
      .map(route => route.component);
  if (components.length > 0 && (components[0].fetchData instanceof Function)) {
    components[0]
      .fetchData(req.query, req.path)
      .then((response) => {
        renderView(req, res, response);
      })
      .catch((error) => {
        try {
          console.log('--- ssr render error --- ', error);
        } catch (e) {
          console.log('--- ssr render error catch--- ', e);
        }
        renderView(req, res, {});
      });
  } else {
    renderView(req, res, {});
  }
}

module.exports = handleRender;

Observe that we removed using JssProvider , generateClassName, Stylesheet Manager etc. The latest changes are much simpler

App.js file changes

import React, { Component } from 'react';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
// import JssProvider from 'react-jss/lib/JssProvider';
// import {
//   MuiThemeProvider,
//   createMuiTheme,
//   createGenerateClassName
// } from '@material-ui/core/styles';
import { ThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { applyMiddleware, createStore } from 'redux';
import { BrowserRouter } from 'react-router-dom'
import green from '@material-ui/core/colors/green'
import red from '@material-ui/core/colors/red';
import Routes from './Routes';
import reducers from './Reducers';

const middleware = applyMiddleware(thunk);
const initialState = window.INITIAL_STATE;
const store = createStore(reducers, initialState, middleware);

// Create a theme instance.
const theme = createMuiTheme({
  palette: {
    primary: green,
    accent: red,
    type: 'light',
  },
});
// const generateClassName = createGenerateClassName();

class App extends Component {
  componentDidMount() {
    //Not required to remove css since it is already came from sssr
    // const jssStyles = document.getElementById('jss-server-side');
    // if (jssStyles && jssStyles.parentNode) {
    //   jssStyles.parentNode.removeChild(jssStyles);
    // }
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles) {
      jssStyles.parentElement.removeChild(jssStyles);
    }
  }
  
  render() {
    return (
      <Provider store={store}>
        <BrowserRouter>
          {/* <JssProvider generateClassName={generateClassName}> */}
            <ThemeProvider theme={theme} >
              {Routes}
            </ThemeProvider>
          {/* </JssProvider> */}
        </BrowserRouter>
      </Provider>
    );
  }
}

export default App;

Again we no need to use JssProvider in client side as well.

These changes will solve the issue.

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

Sequelize one-to-many relation can be defined using belongsTo and hasMany methods. but before moving on to one-to-many I suggest readers to go through my previous post on one-to-one relation.

Defining One-To-One relation in Sequelize

Now let us consider a school management system when we define relation between Subjects and Chapters. One subject has many chapters. The database schema looks as follows.

Master Subjects Entity

const MasterAcademicsModel = require('../Models/MasterAcademicsModel');
const MasterBoardsModel = require('../Models/MasterBoardsModel');
const MasterClassModel = require('../Models/MasterClassModel');
const MasterMediumsModel = require('../Models/MasterMediumsModel');


const MasterSubjectModel = db.define(
  "master_subjects",
  {
    subjectId: {
      field: "subjectId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4,
    },
    name: {
      field: "name",
      type: sqlOperator.STRING(100),
      allowNull: false,
    },
  },
  {
    tableName: "master_subjects",
    timestamps: true,
  }
);

MasterSubjectModel.associate = async () =>{
  await MasterSubjectModel.belongsTo(MasterAcademicsModel,{
    foreignKey: 'masterSubjectAcademicId',
    targetKey: 'academicId'
  });
  await MasterSubjectModel.belongsTo(MasterBoardsModel,{
    foreignKey: 'masterSubjectBoardId',
    targetKey: 'boardId'
  });
  await MasterSubjectModel.belongsTo(MasterMediumsModel,{
    foreignKey: 'masterSubjectMediumId',
    targetKey: 'mediumId'
  });
  await MasterSubjectModel.belongsTo(MasterClassModel,{
    foreignKey: 'masterSubjectClassId',
    targetKey: 'classId'
  });
}

module.exports = MasterSubjectModel;

Chapters Model


const ChapterModel = db.define(
  "chapters",
  {
    chapterId: {
      field: "chapterId",
      type: sqlOperator.UUID,
      primaryKey: true,
      defaultValue: sqlOperator.UUIDV4,
    },
    title: {
      field: "title",
      type: sqlOperator.STRING(100),
    },
    tags: {
      field: "tags",
      type: sqlOperator.STRING(100),
    },
  },
  {
    tableName: "chapters",
    timestamps: true,
  }
);

ChapterModel.associate = async () => {
  console.log(
    "--- Establishing relations between chapter and chapter content ---"
  );
  const MasterSubjectModel = require("./MasterSubjectModel");
  const ChapterContentModel = require("./ChapterContentModel");
  const MasterAcademicsModel = require("./MasterAcademicsModel");

  await ChapterModel.belongsTo(MasterSubjectModel, {
    foreignKey: "masterSubjectId",
    targetKey: "subjectId",
    as: "subject",
  });
  await MasterSubjectModel.hasMany(ChapterModel, {
    foreignKey: 'masterSubjectId',
    sourceKey: 'subjectId',
  });

  await ChapterModel.belongsTo(MasterAcademicsModel, {
    foreignKey: "masterAcademicId",
    targetKey: "academicId",
    as: "academic",
  });
  await MasterAcademicsModel.hasMany(ChapterModel, {
    foreignKey: 'masterAcademicId',
    sourceKey: 'academicId',
  });

  await ChapterModel.hasMany(ChapterContentModel, {
    foreignKey: 'chapterId',
    sourceKey: 'chapterId',
    as: "chapterContents",
  });
  await ChapterContentModel.belongsTo(ChapterModel, {
    foreignKey: "chapterId",
    targetKey: "chapterId",
  });
};

module.exports = ChapterModel;

Notice here that to define One-To-Many both belogsTo and hasMany method are used. you can define the relation using only belongsTo method, however you will endup with multiple sequelize errors. To avoid sequelize errors while fetching data using find method on one-to-many relation, kindly update your models by defining relation in both ways.

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(
  'users',
  {
    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(
  'user_profiles',
  {
    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.

Read more about Defining One-To-Many relation using sequelize

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

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 references for Highly Scalable 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

Uber has a micro-service architecture.

  1. Netflix Architecture – Reference Click Here

Netflix architecture looks very complex and it is micro-service architecture

Some highlights of Netflix Architecture, Hundred’s of microservices and one giant service. thousand’s of servers spread across the world, thousand’s of Content Delivery Networks, Netflix uses their own CDN called Open Connect

  1. 100s of microservices
  2. 1000s of daily production changes
  3. 10,000s of instances running in AWS cloud
  4. 10, 000, 000, 000 hours of streamed

This is how it looks 🙂

Reference: How Netflix works: the (hugely simplified) complex stuff that happens every time you hit Play

  1. Ebay Architecture

Read More on Platform Architecture

Thank You

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

Platform Architecture in Computer Science: Different approaches and Benefits

What is Platform Architecture in Computer Science

A platform architecture is an abstract high level design of the platform that answers to some of the key important factors of any platform like scalability, resilience, maintainability. It should cover almost all important big modules, multiple apps, all the servers, databases, caching, third party solutions and etc.

A platform should be ever evolvable, should be able to adopt to the new changes and needs of the platform and it helps to meet all technical and operational requirements with focus on optimising performance and security.

Desirable Properties of Platform Architecture

  1. High level of Abstraction – It should be simple enough and comprehensive enough to get high level of understanding
  2. Resilient – Each major module (app) should not be get affected so much due to one defective app
  3. Scalable – Architecture should consider the scalability of the platform “Scalability” refers to the number of users, sessions, transactions, and operations that can be accommodated by the entire system
  4. Maintainable – Should be able to make changes to any part of the system without breaking or damaging too much to other parts
  5. Ever Enhancing – it should be able to evolve every-time when there is a need of change

Important Aspects to focus on while designing platform architecture.

  1. How many servers we need to maintain, is it per app level or every major functionality
  2. How caching is handled in platform
  3. API Gateways for API security, metering, throttling
  4. Searching functionality within the platform
  5. Users and Identity Management
  6. Security
  7. Databases
  8. File Servers
  9. Third Party Services if any
  10. Data query and Manipulation for faster data access like using GraphQL
  11. Communication between each apps or each servers using event queue, event bus or intermediate app whichever way it is
  12. Handling batch processes using cronjobs or cloud functions
  13. Data mining, AI System

For Different Approaches for designing Platform Architectures click here