Skip to content

AI & Automation

Two-way sync between HubSpot and PostgreSQL without duplicates

Duplicates between HubSpot and PostgreSQL rarely come from an isolated bug. Shared IDs, a system of record per field, upserts and reconciliation: how to prevent them.

By Lenobot Engineering

  • 11 min read
Two-way sync between HubSpot and PostgreSQL without duplicates

Syncing HubSpot and PostgreSQL both ways without duplicates comes down to four decisions to make before writing any code: a stable identifier known to both systems, a system of record for each field, idempotent writes (safe to replay without creating anything extra) and a regular check that compares the two databases. Duplicates rarely come from an isolated bug: they come from matching on email addresses, badly handled retries or two processes running at the same time.

In short

  • Link records through a technical identifier stored on both sides, never through the email address alone.
  • Assign every field to a system of record: most conflicts disappear before they exist.
  • Replace "search, then create" with a write that creates or updates in a single operation, keyed on a unique value.
  • Break loops by writing only what has changed and by recognizing the sync's own writes.
  • Add a periodic reconciliation: HubSpot notifications can arrive twice, late or out of order.

Why duplicates appear

Take a hypothetical SaaS vendor: its product, backed by PostgreSQL, pushes sign-ups and usage to HubSpot, which sends back the assigned sales rep and the lifecycle stage. Five mechanisms create duplicates or overwritten data in this setup:

  • Matching on email. A user changes address, or signs up with a personal address while the sales rep entered the work one: the sync does not recognize them and creates a second contact.
  • Companies. HubSpot automatically deduplicates contacts on email, but companies created through the API (sync apps included) are not deduplicated on their domain name: your integration has to handle it.
  • The "search, then create" sequence. Two events in quick succession for the same customer account (workspace creation, then a colleague invitation) trigger two searches that find nothing, then two company creations. HubSpot's documentation states that a recent record can take a few moments to appear in search results.
  • Retries. A create call times out even though HubSpot executed it; the program retries and creates a duplicate, unless a unique key prevents it.
  • Merges and loops. After a merge in HubSpot, the surviving record gets a new ID by default, one the product database does not know. And without safeguards, a value written by the sync comes back to PostgreSQL as a new change, then goes out again, endlessly.

None of these causes can be fixed with a one-off cleanup: they have to be handled in the design.

A stable identifier on both sides

The principle: link records through technical identifiers, exchanged once and then kept, rather than through business data (email, name, domain).

On the PostgreSQL side, add a column for the HubSpot ID to the user and account tables, with a uniqueness constraint. On the HubSpot side, create a custom property that holds your product's identifier and mark it as unique: HubSpot allows up to ten such properties per object, and they can be used as a key to read or update a record.

The sync then no longer needs to search before creating. It uses the API's "upsert" operation (create or update in a single call) with the product identifier as the key. Replayed ten times, the same operation produces a single record.

Email addresses then serve only two purposes: the initial migration, and the prospect created first in HubSpot (form, trade show, import) who later signs up for the product. In that second case, the sync attaches the product identifier to the existing contact instead of creating a new one, after normalizing the address (lowercase, spaces removed).

Two cases need planning from day one. Merges: HubSpot can notify your app of a merge, with the merged IDs and the ID of the surviving record; update the mapping table at that point. If both records carried a product identifier, the merged record keeps only one: left unhandled, the next upsert for the other one will recreate the record that disappeared. Companies: store the customer account's identifier on the company object and do not rely on the domain alone, which subsidiaries sometimes share and which tells you nothing when it belongs to a consumer email provider.

A system of record for every field

"Two-way" does not mean every field flows in both directions. In most cases, we recommend the opposite: every field has an owner, and only a few truly shared fields need an arbitration rule.

Data typeSystem of recordDirectionConflict rule
Identifiers (product, HubSpot)Each system for its ownExchanged onceNever changed by the sync
Plan, subscription status, usagePostgreSQLProduct to CRMThe product always wins
Assigned rep, lifecycle stage, segmentHubSpotCRM to productHubSpot always wins
Contact details (name, phone, job title)SharedBoth waysMost recent change, field by field
Marketing consentSharedBoth waysThe person's latest explicit decision

Three precautions make these rules workable:

  • Flag the product-fed fields in HubSpot (a dedicated property group) and restrict editing where possible: a rep who corrects a subscription status by hand would see the change overwritten without understanding why.
  • For shared fields, compare modification dates field by field, not record by record. HubSpot keeps a timestamped history of each property; on the PostgreSQL side, you need a history table or a date per field. Otherwise, a phone number corrected in the CRM will overwrite a name corrected in the product.
  • Send sensitive conflicts to human review, for example on a strategic account.

These arbitration rules are business decisions: they are set with the sales team, not just with developers.

Capturing changes and writing without side effects

On the PostgreSQL side, avoid triggers that call HubSpot directly: a failed call either fails the business transaction or gets lost without a trace. Use the "outbox" pattern instead: the business change and a message describing it are written in the same transaction, then a separate process forwards these messages. At high volume, PostgreSQL's logical replication can also read changes straight from its log.

On the HubSpot side, there are three options: webhooks (HTTP notifications sent to your server on each change), the event journal in recent API versions, readable in chronological order over three days, or periodic polling of records modified since the last run, with an overlap margin. On webhooks, HubSpot's developer documentation is explicit: arrival order is not guaranteed, and the same notification can arrive more than once, although this is rare. A server that takes more than five seconds to respond, or returns an error, triggers new attempts, up to ten over twenty-four hours.

The resulting rules:

  1. Acknowledge receipt immediately, store the event, then process it in the background.
  2. Treat the notification as a signal: re-read the record's current state from the API before writing, which solves the ordering problem.
  3. Process only one event at a time per record (a queue partitioned by ID, or a lock).
  4. Do not deduplicate on the event ID alone, which HubSpot does not guarantee to be unique: idempotency relies on upserts by unique key and on absolute values rather than increments.
  5. Break loops: remember the last values written by the sync and ignore any notification that merely echoes them back. The change source, included in the notifications, helps with this filtering.
  6. Respect call limits: HubSpot caps requests per ten-second window and per day, depending on the app type and subscription, then returns a 429 error. Batch your writes, retry with increasing delays and put persistent failures in a monitored queue.

Off-the-shelf tool or custom build

What remains is choosing where to apply these principles.

OptionSuited whenMain limits
Automation platform (n8n, Make, Zapier)Few fields, modest volumes, one dominant directionMapping table, idempotency and ordering to build yourself, logic scattered across scenarios
Native Data Hub featuresData Hub Enterprise subscription, a lag of several hours is acceptablePeriodic one-way flows, features in beta, HubSpot credits to budget for
Specialized sync toolStandard needs, or a data warehouse already in placeExtra subscription, arbitration limited to what the tool offers
Custom sync serviceProduct data at the heart of the sales relationship, specific rulesDevelopment, testing and monitoring to own over time

Natively, Data Hub Enterprise offers in beta a PostgreSQL connector in Data Studio, whose data can then feed the CRM, and an export from HubSpot to your database ("Data Out"): two periodic one-way flows, subject to the same field ownership rules.

If you start with an automation platform, apply the same rigor; our practical guide to n8n workflows covers how a workflow is structured, retries and error handling. As volumes grow or arbitration rules multiply, a dedicated service, backed by PostgreSQL for the mapping table and the event queue, becomes easier to make reliable. This is the kind of project our process automation offering covers. And if your CRM choice is not settled yet, our comparison of Pipedrive, HubSpot, Salesforce and Notion helps you decide before investing in the integration.

Going live and keeping the sync healthy

Go-live often creates the most duplicates: it connects two databases that have lived separate lives. A careful sequence:

  1. Export both databases, normalize emails and domains, match records and send ambiguous cases to human review.
  2. Merge existing duplicates in HubSpot, then write the cross-referenced IDs on both sides.
  3. Turn on one direction first, usually product to CRM, and check that there are no discrepancies before opening the reverse direction.

Plan for deletions too. A contact deleted in HubSpot goes to the recycling bin and can be restored; a user deleted in the product must not be recreated on the next run. Keep a minimal record of each deletion (the technical ID only, with no name or contact details) so the sync knows an absence is intentional. A GDPR erasure request (Article 17) must be carried out in both systems, without the sync bringing the person back.

Finally, measure: a nightly reconciliation flags records present on only one side, diverging fields and new duplicates. Also track propagation delay, the failure queue and the number of arbitrated conflicts: an alert beats a sales rep discovering the discrepancy in front of a customer.

Frequently asked questions

Not as the primary key: addresses change, people use several, and a generic address can refer to several people. Email is useful for the initial migration and for linking an existing prospect to their sign-up, after normalization.

Ideally both. Webhooks bring responsiveness, but a notification can be lost if your server stays unavailable beyond the retries; periodic reconciliation fills those gaps. If a delay of a few hours is acceptable for your teams, periodic sync alone may even be enough.

Deal with them before go-live. HubSpot offers a duplicate management tool with Professional and Enterprise subscriptions, and merges, which are permanent, can also be done through the API. Then update the mapping table with the surviving IDs, and turn on the sync.

Rarely. For selling, a few aggregated indicators are enough: last login date, number of active users, key features enabled. Sending every action uses up API calls, clutters records and complicates the sync, while the GDPR requires limiting data to what is necessary.

Conclusion

A two-way sync without duplicates depends less on the tool than on a few early decisions: technical identifiers exchanged once, an owner for every field, writes that can be replayed without side effects and a reconciliation that checks the whole thing. These rules avoid repeated cleanups and keep a CRM the sales team trusts.

If you are preparing to connect your product to HubSpot, or want to make an existing sync more reliable, let's talk about your context.

Written by

Lenobot Engineering

We design, build and maintain websites, business applications and AI systems. Our articles share the methods we apply on our projects.

About the studio