Skip to content

About

Code to enable mirroring in Microsoft Fabric for MongoDB

Resources

Stars

11 stars

Watchers

4 watching

Forks

Latest commit

 

History

132 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MongoDB to Microsoft Fabric Mirroring

This project is for enabling mirroring which can replicate MongoDB Atlas Data with Microsoft Fabric One Lake in near real time.
It requires two main steps:

  1. Creating the Fabric mount point also called Landing Zone or MirrorDB
  2. Deploy Code to run in an App service using Deploy to Azure button below or to a VM by cloning the Git repo and running the app.py script.
    Once started, app will continously keep track of the changes in MongoDB Atlas and replicate them to the MirrorDB created in Step 1.

Follow below steps if you want to create manually using Fabric UI (Step 1) and by one click on "Deploy to Azure" below (Step 2) OR you can use the Terraform template provided in the "terraform" folder.
The Terraform template also provides ability to create a private connection between the App Service and MongoDB Atlas.

Versioning and releases

  • Runtime version — VERSION in the repo root (also constants.APP_VERSION). Logged at mirroring startup.
  • Change log — See RELEASE_NOTES.md for version history and how to create Git tags (e.g. v1.3.0).

Step1: MirrorDB Creation

To create the MirrorDB, we use the Fabric UI.

Follow the steps below for the MirrorDB (LZ) creation.

  1. Click on the “+ New Item” in your workspace.
MirrorDB_1


2. In the pop up window that opens, select “Mirrored Database (preview)” MirrorDB_2


3. Give a name for your new MirrorDB. MirrorDB_3


4. The new MirrorDB creation will begin and the screen shows the progress of the same. MirrorDB_5

  1. The new MirrorDB creation is complete when you see the below screen showing that replication is “Running”. Note that you can get the LandingZone url also from this screen.
MirrorDB_6 **Also, note that you may have to add “/” at the end of this url when you trigger the mirroring script.**


6. You can also verify the LandingZone folder created within the MirrorDB in Azure storage explorer. How to access your LZ in Storage Explorer is detailed in Step2: Start Mirroring -> Pre-requisites for Step2 -> Point #2 MirrorDB_7

Step2: Start Mirroring

Step 2 is basically executing the ARM template by clicking the Deploy to Azure button. But, we need to get the parameters to be provided to the ARM template ready beforehand.

Pre-requisites for Step2:

  1. Keep the MongoDB Connection uri, Database name and Collection name handy for input in ARM template. Note you can give multiple collections as an array ["col1", "col2"] or can give "all" for all collections in a Database.
  2. Install Azure Storage explorer. Connect to Azure Storage by selecting Attach to a resource -> ADLS Gen2 container or directory -> Sign in using Oauth. Select your Azure login id and on next screen give the Blob container or directory URL as https://onelake.blob.fabric.microsoft.com/<workspace name in Fabric>. Once connected you can see the Workspace under Storage Accounts -> (Attached Containers) -> Blob Containers. Double click your Workspace, you should see the MirrorDB folder. You should also have a LandingZone folder within Files folder. You can always check for parquet files in this folder which will get replicated to OneLake and shown as tables in OneLake.

image

  1. For authentication, its through Service Principal and so we need to go to App Registrations in Azure portal and register a new app. Also create a new secret in the App. Get the Tenant Id, App Id and the value of the secret for input in ARM template. the secret value should be copied when being created, you will not be able to see it later.

image

image

  1. Go to Fabric Workspace -> Manage Access -> Type in the new App name -> Select the App and give it admin permissions to write to this workspace. Select Add people or groups if you donot already have the App in your list.

image

Refer to .env_example for the parameters needed.

Step2 Execution

Option 1 (on local / Azure VM)

If running on local or a VM, clone this repo, populate all parameters in .env_example and rename it to .env. Then just run python app.pyto start the app and thus start replication from MongoDB Atlas collection OneLake MirrorDB's table.

Option 2 (on Azure App service)

Clicking below button, will take you to Azure portal, give in the values for the parameters along with the App service specific parameters and click Deploy. Once App service is deployed, Go to the resource and watch Log stream to see if the app had started. After the app service is deployed, it will take 10 - 15 mins for the app to be deployed onto the App service and started.

Please don't click on the App url before the deployment is complete and logs from the App start showing up.

Click below to start your App service for MongoDB to Fabric replication:

Deploy to Azure

Best Practices and Troubleshooting

  1. Please note the code runs initial sync synchronously per collection, then starts a listening (change stream) thread. For large collections (~10 Million+ records), be judicious in selecting the compute size of the App service or VM. As a high level bench mark, a compute of 4 CPUs, 16 GiB of memory might work for 5 such collections with a high throughput of say 1000 records/second. Beyond, that we should really monitor the performance and threads and check the CPU usage.
  2. Azure Storage explorer is your point to start the troubleshooting. Use below files that start with an underscore to get vital information. (They are not copied to OneLake as they start with underscore"_"). Also note these are pickle files and you can view them using command "python -mpickle _maxid.pkl” in terminal.
    a. _max_id file: Will tell you what was the maximum _id field that was captured before initial sync began. All records with _id <= this _max_id are copied as part of initial_sync. b. _init_cluster_time: BSON Timestamp N captured at init start. Used so the change stream can start at N+1 until a resume token exists. c. _resume_token: Contains the last resume token of the real time change event copied to LZ. Thus, you see this file only if atleast one real time changes parquet file was written in LZ.
    d. _initial_sync_status: Indicates initial_sync is complete or not. "Y" in this file will indicate that initial_sync is complete.
    e. _metadata.json: Has the primary key which is always "_id". This file should exist in a replicated folder/ table for mirroring to work.
    f. _last_id: This is the "_id" value of the last record of the last initial sync batch file written to LZ. This file is deleted when initial sync is completed.
    g. _internal_schema: This is one of the very first files written and has the schema as of the records in the collection being replicated.
  3. Internal schema is inferred from a random $sample of the collection. By default the sample size is below 5% of estimated_document_count (4.9% in code). Set SCHEMA_BOOTSTRAP_SAMPLE_SIZE in .env to an explicit document count if you need a smaller or larger cap (still clamped to the collection size). For very large collections, prefer a bounded override to limit startup read cost.
  4. Restartability: after init completes, listening uses _resume_token when present; otherwise it uses _init_cluster_time (startAtOperationTime = N+1) so changes after the captured cluster time are not missed when the listening thread starts. If init sync fails mid-way, the same frozen N and _last_id / _max_id are reused on resume. If the process fails before init completes and you need a clean re-baseline, delete the collection folder in the landing zone (including _init_cluster_time) and restart.
  5. Also, if you are using App service option to host the solution and are observing that App Service is not reflecting the latest code or not starting the code, an observation shared to us by one of the customers was that in App configuration settings - "Always On" needs to be on, and "Session Affinity" needs to be off. Please validate this for yourself and check if it is making the App Service behave nicely :-)

Known Limitations

  1. This solution is based on MongoDB Atlas changestreams to capture the real time changes and sync them to Fabric OneLake. And because changestreams are not yet supported for Timeseries collections, the current solution will not work for Timeseries collections.
  2. The CRUD operations events captured are Insert, Delete and Update. MongoDB Replace operation is not handled as Open mirroring doesn't support it as a valid action.

Appendices

Test document

Here is a test document for the integration app validation, with all data types supported by MongoDB documents:

{
  "_id": {
    "$oid": "69f96bebe6d817f45eefc846"
  },
  "doubleField": 1.23,
  "stringField": "hello",
  "objectField": {
    "a": 1,
    "b": "x"
  },
  "arrayField": [
    1,
    "two",
    {
      "three": 3
    }
  ],
  "binaryField": {
    "$binary": {
      "base64": "AQID",
      "subType": "00"
    }
  },
  "undefinedField": null,
  "objectIdField": {
    "$oid": "69f9563395423819b6dba160"
  },
  "boolField": true,
  "dateField": {
    "$date": "2024-01-01T00:00:00.000Z"
  },
  "nullField": null,
  "regexField": {
    "$regularExpression": {
      "pattern": "abc",
      "options": "i"
    }
  },
  "dbPointerField": {
    "$ref": "otherCollection",
    "$id": {
      "$oid": "64cba4e7e3f1f1a1b2c3d4e5"
    }
  },
  "jsField": {
    "$code": "function() { return 1; }"
  },
  "jsWithScopeField": {
    "$code": "function() { return x; }",
    "$scope": {
      "x": 42
    }
  },
  "int32Field": 42,
  "timestampField": {
    "$timestamp": {
      "t": 1,
      "i": 1
    }
  },
  "int64Field": {
    "$numberLong": "9007199254740991"
  },
  "decimal128Field": {
    "$numberDecimal": "1234.5678"
  },
  "minKeyField": {
    "$minKey": 1
  },
  "maxKeyField": {
    "$maxKey": 1
  }
}

On Microsoft Fabric Mirrored Database, the fields will be converted to the following:

COLUMN_NAME DATA_TYPE
_id varchar
doubleField float
stringField varchar
objectField varchar
arrayField varchar
binaryField varchar
undefinedField varchar
objectIdField varchar
boolField bit
dateField datetime2
nullField varchar
regexField varchar
dbPointerField varchar
jsField varchar
jsWithScopeField varchar
int32Field bigint
timestampField varchar
int64Field bigint
decimal128Field float
minKeyField varchar
maxKeyField varchar

About

Code to enable mirroring in Microsoft Fabric for MongoDB

Resources

Stars

11 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages