simrayz

simrayz

I’m using a Neo4j database to supplement my Postgresql database. Postgres is used to store the entities themselves (e.g. users), and should always be the one source of truth. However, I am struggling with figuring out how I make sure the Neo4j database consistent with my postgres database. I am using Ecto and Bolt.Sips as my database adapters.

How can I make sure that a user is only created/deleted/changed if the action is successful in both databases? Both Ecto and Bolt.Sips has transaction/rollback functionality, but is there a way to combine them?

This is what I have so far, but this would cause problems if the postgres transaction fails after the neo4j transaction has finished.

def delete_user(%User{} = user) do 
  Ecto.Multi.new()
  |> Ecto.Multi.delete(:delete, user)
  |> Ecto.Multi.run(:delete_neo4j, fn _, _ ->
        Neo4j.Accounts.delete_user(user)
  |> Repo.transaction()

Showing Posts 1 to 10

lpil

lpil

Creator of Gleam

There’s no simple way to have transactional behaviour across two database. You could look into implementing patterns such as the saga pattern but this is a lot of work and easy to get wrong.

The more straightforward solution may be to manually write some undo logic for the Neo4j database that runs after a postgresql transaction fails, but this will be error prone and imperfect.

I would be tempted to remove the Neo4j database if possible and move the graph queries into postgresql using recursive queries.

simrayz

simrayz OP

The reason we’re using Neo4j is to handle complex relationships. For example, we have containers of widgets, that can be connected to other containers. Containers can also subscribe to widgets of other containers.
Another reason is that access permissions are not necessarily granted directly (as in user has permissions on container), but by checking if the user has permissions somewhere in the hierarchy. E.g. user A is an admin in organization B, which has a group C with a container D. Simply by being an admin in B, user A should have permissions on container D.

Would you still opt to model it in postgres, despite there being a potential for many levels of joins?

lpil

lpil

Creator of Gleam

I would build the system using the existing postgresql database and recursive queries, and then benchmark the system with generated production-like data to measure performance to see if an alternative approach is needed.

If the performance of postgresql is sufficient (in my case it was) I would go that way as (in my opinion) if offers a better operational and development experience while offering better durability and data integrity guarantees. In addition use of single database means we can use database transactions :slight_smile:

If I were to use both I would likely write to Postgres in the transaction (as the primary datastore and source of truth) and then replicate a subset of that information to Neo4j for faster querying with eventual consistency.

WolfDan

WolfDan

I ran into this problem before with an app I’ve worked for a while, as @lpil mentioned there’s no simple way to have two transactional behaviours, depending on the app using postgres only is the right solution, but I’ve work with graphs and I know there’s way too many benefits over a relational one on some use cases

In this case I’d recommend you look into another solutions that guarantee consistency over the whole single database while maintaining the graph data structure

GitHub - skaiworldwide-oss/agensgraph: AgensGraph, a transactional graph database based on PostgreSQL · GitHub a graph database on top of postgres, you’ve both sql and graph queries available and you can combine them as well, the problem is documentation, is hard to get started

https://dgraph.io/ it’s a distributed and acid complaint database, it’s supposed to be the same as postgres consistency while being graph and distributed, tho in my time I was using it the dev team was quite “problematic” and didn’t focus well on what they want to do, so I stop using it, I don’t know the actual status of the dev team right now but seems like everything is going fine now

GitHub - cayleygraph/cayley: An open-source graph database · GitHub this is more like a plugin for many databases, it works for postgres too so you can do the same as agens graph, documentation is a problem as well

In my case I just end up using https://www.foundationdb.org/ and creating a graph like layer myself (GitHub - OkamiIO/Nomure: A proof-of-concept graph Database on top of FoundationDB · GitHub , I’ve another version but is not released yet, once is finished I’ll share it for the moment the code you saw there is not the best),

There’s another graph layer for fdb like GitHub - JanusGraph/janusgraph-foundationdb: FoundationDB storage adapter for JanusGraph · GitHub tho is not complete afaik. The folks at Ebay made a new layer on top of janusgraph and fdb but they have not released it (yet?), for more info check here FoundationDB Summit 2019: NuGraph: GraphDB as a Cloud Service Built Upon JanusGraph and FoundationDB - Community - FoundationDB

domvas

domvas

Using only ecto, it’s not possible to manage a transaction on both postgres and neo4j at the same time.
To do so use existing pattern like saga as @lpil said or implement your own system: having a transaction on top on the two other, use events to do / undo operation, having ‘Temp’ label in Neo4j, etc.

Well, everyone seems to show the way to “put all your data in postgres”. But why not the opposite? Is having all the data is Neo4j so horrible? (Well, if you plan to do mostly statistics, yes it’s awful…)
What offers postgres that couldn’t be done by Neo4j? (except that they are not designed for the same purpose :slight_smile: )
And keep in mind that if you don’t do “heavy” traversal queries, you probably don’t need Neo4j. If all your requests can be express with Ecto.Query, then you don’t need Neo4j.

And this:

If I were to use both I would likely write to Postgres in the transaction (as the primary datastore and source of truth) and then replicate a subset of that information to Neo4j for faster querying with eventual consistency.

works very well.
But it depends on wether you need to serve ultra fresh data or not.
Again, trade-off…

yourpalal

yourpalal

I’m going to be contrarian and suggest that yes, this is possible!

You need to use a 2-step transaction in postgres (PostgreSQL: Documentation: 9.3: PREPARE TRANSACTION)

Basically it goes like this:

postgres: BEGIN TRANSACTION
neo4j: BEGIN TRANSACTION

...

postgres: PREPARE TRANSACTION
if failed, neo4j: ROLLBACK
neo4j: COMMIT
if failed: postgres ROLLBACK PREPARED
postgres: postgres COMMIT PREPARED

the key being the PREPARE feature in postgres. This allows you to almost commit a transaction, with the possibility of rolling it back. The transaction is pretty much committed at that point, and any database checks such as constraints etc. have passed. Then you can commit neo4j knowing the postgres data is safe, and then finally finish up the postgres commit by telling postgres that it’s okay to finalize that transaction.

I’m not sure what the performance implications are but this is the safest way to do it.

Edit: It looks like postgrex doesn’t have native support for this but I feel like it would probably not be that hard to either:

  1. make a PR To support it
  2. hack it into your codebase in some way
OvermindDL1

OvermindDL1

Well if there is a neo4j FDW plugin for postgresql, then postgresql could do the cross database transaction as well as any is possible. :slightly_smiling_face:

FDW plugins let you use another database from inside pgsql itself, I use it and it works well, is not a touch slower but hey joining across makes up for it! :grin:

sorentwo

sorentwo

Oban Core Team

Storing data in both Neo4J and Postgres isn’t something I recommend. As mentioned earlier in this thread, something should be the source of truth and then you can replicate to another data store for querying.

There is a great talk on this exact situation by Glen Vanderburg at RailsConf a few years back (this was a project I was initially involved in): https://m.youtube.com/watch?v=Nz-aU3vOFbw

simrayz

simrayz OP

Thanks for a lot of good answers!

From what I’ve gathered, using Neo4j as document storage is not the best idea (it doesn’t scale well). However, a lot of projects use a combination of MongoDB as document storage and Neo4j for metadata. I’m thinking that Postgres should be able to fill the role of document storage just as well, as it can store json documents and keep separate fields for what needs to be queryable. Is using Mongo + Neo4j a good idea, and if so, why is this not also the case for Postgres + Neo4j?

The reason for using Neo4j is to simplify modeling of complex structures such as permission hierarchies, as it can be queried and examined exactly as it’s stored, but also to make queries faster when they get several levels deep. I feel like “don’t do it” is a bit of a rash decision, as there’s no doubt that graph databases excel at both these points. However, I can’t find a single record of someone combining Postgres + Neo4j, so I do feel like I’m doing something wrong :sweat_smile:

lpil

lpil

Creator of Gleam

I think with Mongo + Neo4j you’ll likely have a lot of the same problems as with Postgres + Neo4j. Mongo vs Postgres is probably a matter of personal preference in many ways, but I would go for Postgres even if I wanted a document database (using Postgres JSONB).

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
aseigo
ICal is a library for interacting with iCalendar data. It parses iCalendars into typed Elixir structs via ICal.from_ics, and can prepare ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews