Websites tend to reflect the local markets. In Southeast Asian traditional markets, two things are certain:
- Bargaining
- Vendors’ talent of reading micro-expressions on a passerby to predict the likelihood of purchase.
The combination of these two means that vendors can intervene with a better offer in the right moment, before they lose a potential customer.
This amazing art is often lost in today’s e-commerce world. Someone lands on the website, scrolls, clicks, adds some goods to their basket, and then poof! The customer is gone.
While tracking session behaviour to convert to purchase is not a new phenomenon in the data landscape, most actions take place after the session: follow-up email in a day, consolidated reports in a week, etc.
What if we could mimic the real-time vendor’s spider sense and make the magic happen in the e-commerce world too?
This is where real-time Machine Learning inference comes in.
In this article, we will explore a common e-commerce use case of predicting purchase intent. We will show you how to set up the solution with Snowpark Container Services (SPCS) and Snowflake Registry to leverage real-time ML inference efficiently.
Why Snowpark Container Services (SPCS)?
If your organisation already runs on Snowflake, SPCS is the smart way to bring the ML capabilities into production seamlessly, securely, and without the hassle of managing separate infrastructure.
What is SPCS?
Snowpark Container Services is a fully managed container runtime inside Snowflake that enables you to deploy and run custom services, including ML models, Python apps, and APIs, directly alongside your data, using the same governance, security, and scalability within the Snowflake ecosystem you already trust.
Under the hood, SPCS is powered by a Kubernetes core, giving you the same flexibility and orchestration capabilities as modern cloud-native platforms, without ever needing to touch a cluster.
It supports automatic scaling, adapting instantly to demand by scaling up for peak workloads and back down to save costs. All of this is managed in a seamless, automated way within Snowflake itself.
One of the most important advantages this gives you is the ability to easily deploy a service that leverages the ML model using SQL-native inference for fast wins, or unlock full power with custom batch jobs, streaming, or RESTful APIs, all in the familiar environment where your data lives.
Model serving in SPCS
The Snowflake Model Registry lets you serve models either on a warehouse or via Snowpark Container Services (SPCS).
Warehouse-based serving is great for lightweight, CPU-only models with limited dependencies. SPCS goes a step further and removes those limits. You can run larger models, use any Python packages (including from PyPI), and even scale across GPU clusters. Best of all, you do not need to manage containers or Kubernetes, as Snowflake handles it all behind the scenes.
While the SPCS deployment seems to be the more powerful approach, Snowflake handles the complexity, automatically building the container, service image, packaging dependencies, and spinning up the inference server.
Demo: predicting purchase intent in e-commerce in real time
In this demo, we use the Retail Rocket dataset from Kaggle to replicate a common real-life use case in the e-commerce industry, namely predicting the likelihood that a user session will lead to a purchase.
This mirrors what many online retailers do behind the scenes: tracking user interactions in real time and using ML to decide:
- Whom to target with a promo during the session;
- Whom to follow up with after they leave;
- Whom to include in marketing campaigns.
Dataset: Retail Rocket (Kaggle)
The dataset contains over 2.7 million raw events, including:
- view: when a product page is viewed;
- addtocart: when an item is added to the cart;
- transaction: when a purchase occurs;
- Plus metadata on items and categories.
These event logs are typical of real-world ecommerce tracking systems, making the dataset ideal for simulating production scenarios.
Model: RandomForestClassifier (Scikit-learn)
To model the purchase intent, we use RandomForestClassifier, a popular and production-friendly algorithm for tabular data.
We opted for Random Forest because it is:
- Capable of handling categorical and numerical features well;
- Resistant to over-fitting with the right parameters;
- Easy to interpret and fast to train in our demo;
- Robust even when some features are noisy or missing.
The ideal flow
In real-time systems, each raw event (like a page view, cart add, or click) is logged individually, one action per row. This is great for analytics or tracking, but it is not what the ML model wants.
You do not want to send every single raw event to the ML model and ask, “Should I give a discount now?” Here is why:
- A single event gives almost no signal;
- It wastes compute and…
- It creates noisy, unreliable predictions.
In a nutshell, this will take a huge toll on your model.
On the other hand:
✅ Raw events → flow into a lightweight session cache → balance the latency
✅ Session cache → aggregates over time (e.g. in Redis or in-memory service)
✅ Once enough data → make a call to the ML model for scoring → quality of signal
✅ If the intent score is high → trigger a promotion, nudge, or offer
Note: We have included a data preparation section in the how-to part further in this article.
When should we call the ML inference for prediction?
Obviously, timing matters. The speed at which you apply ML inference is not just a technical detail. It directly determines the type of business action you can take, and whom you are able to influence.
Let’s see just how inference latency shapes action.
All three inference types — SQL, REST API, and Python — run off a single trained model, making it easy to deploy once and serve everywhere with minimal effort.
Once we walk through the implementation steps, we will dive into how ML inference fits into each use case, from real-time to batch.
How-to set up purchase intent prediction
Snowflake objects and privileges
Before deploying the ML model and inference service, we need to prepare the environment inside Snowflake. This one-time setup ensures that the necessary resources, roles, and compute infrastructure are in place.
- Creates a new role, warehouse, database, and schema;
- Grants necessary permissions for model serving;
- Provisions a compute pool for Snowpark Container Services (SPCS);
- Creates an image repository to store container images.
NB: Do ensure that:
- Your Snowflake account has the necessary privileges to create tables and execute ML operations;
- Your warehouse is properly sized for ML workloads (medium-size and snowpark-optimised type).
Setting up the environment
Conda with required packages
To run ML workloads with Snowpark, you will need to set up a dedicated Python environment. We recommend using Conda to manage dependencies cleanly. Simply create a virtual environment with the packages you need (e.g. snowflake-snowpark-python, pandas, scikit-learn) and activate it before running your code.
The official set-up guide is available here.
Training model
Preparing session-level data from raw events
To structure the Retail Rocket event data for ML use, we:
- Parse and sort the event logs by visitorid and timestamp;
- Define session boundaries using a 30-minute inactivity rule. If a user is inactive for more than 1800 seconds, we treat it as the start of a new session;
- Generate a per-user session index (session_id);
- Assign a unique session ID for each event by combining visitorid and session_id to create a globally unique session_uid;
- With over 2 million records, we split the event dataset into two subsets:
- One for training the model;
- One for streaming.
This preprocessing transforms raw click stream data into structured sessions, which is a critical step for both model training and inference.
Training and saving the purchase prediction model
In this step, we trained a Random Forest classifier to predict whether a session would lead to a purchase.
Here is what we did:
- Load the preprocessed session-level dataset;
- Create session-based features to describe user behaviour:
- Number of views, number of cart actions;
- Total events in the session;
- Number of unique items;
- Session duration (in seconds).
- Define the label: A session is labelled as a purchase (e.g. [purchase] = 1, where 1 is the value of the label) if it contains a transaction event;
- Split the dataset into 80% training and 20% testing, with stratification to preserve class distribution;
- Configure and trained the model: We used a RandomForestClassifier with:
- n_estimators=100 trees;
- max_depth=8 to limit overfitting;
- class_weight='balanced' to handle class imbalance;
- Evaluate the model using ROC AUC on both training and test sets to measure how well it distinguishes between buyers and non-buyers;
- Saved the trained model using the joblib package for later use in inference and deployment.
Register the model in Snowflake ML Registry
To make our trained model accessible for inference (via SQL or API), we will register it using the Registry class from the snowflake.ml package.
Main considerations:
- Configure the Snowflake session for the notebook;
- Load the model with joblib package;
- Define model metadata:
- Naming the model name and version;
- Provide a sample input dictionary that reflects your feature set;
- Register the model: call Registry.log_model()with model name, version, and sample input;
- (Optional) Add model tags for version control, lineage and retraining;
- Verify model registration:
- List all registered models with Registry.show_models();
- Retrieve a model using the ModelVersion class;
- View available functions with ModelVersion.show_functions().
Deploying the model to Snowpark Container Services (SPCS)
To serve the model as a live endpoint, we will deploy it using Snowpark Container Services (SPCS), making it callable both via REST API and SQL. To do this, we leverage the Registry class from the snowflake.ml package.
Main points to consider:
- Load the registered model version;
- Registry.get_model(<model_name>).version(<model_version>);
- Deploy the model as a service: Use ModelVersion.create_service() with the following parameters:
- image_repo;
- service_compute_pool;
- ingress_enabled=True: This enables a public endpoint to call the model externally;
- Let Snowflake build your container image: Once triggered, Snowflake will automatically build and deploy the image. You will see logs in the notebook; note that the process may take a few minutes.
Check the outcomes
To check the deployed model and service in Snowflake, we can use either Snowsight (Snowflake UI) or SQL commands.
Please note that in order to check the Snowflake objects, you must use the role with the necessary privileges.
Check the model
Check the service
ML model inference usage
How do you call the ML model?
Via SQL
You can run inference directly in SQL by using Snowflake’s UDF-style syntax.
- Create a test table with feature data that mimics the structure of the ML model input;
- Run predictions using either the model name (registered in the Snowflake Model Registry) or the service name (deployed in SPCS).
Here is the expected output:
Via Python
After registering your model in Snowflake and deploying it to SPCS, you can run predictions programmatically using the snowflake.ml Python API.
Step 1: Load the Model from the Registry:
Step 2: Check available model functions with mv.show_functions(), this returns a list of available functions (e.g., PREDICT) with input/output signatures:
Step 3: Run inference on sample data:
Here is the expected output:
Via the public endpoint
To use this programmatically, leverage the OAuth2 with JWT (JSON Web Token) assertion flow for service-to-service communication. Follow Snowflake's official guide. Here, we show you a simplified walk-through, highlighting the key steps:
This means:
- Row 0 → Prediction = 0
- Row 1 → Prediction = 1
NB: The data in the body format has to match the rule. Note that the first column is the row number within the batch.
Find Snowflake's Guidelines on their website.
Back to the use case
Once the model is trained, registered in Snowflake ML Registry, and deployed to SPCS as a service, we can integrate it into three powerful business flows, each targeting a different stage of the user journey.
Let’s break down how the inference pipeline works in each case:
As a user interacts with the website , client-side event data is captured by an Event Tracker SDK and streamed to a session-level caching layer
.
This session-level caching layer incrementally aggregates event signals in near real time. Once a session reaches a predefined threshold, the system issues a prediction request to the public RESTful endpoint (POST) exposed by the Snowpark Container Services (SPCS) deployment .
The deployed SPCS service invokes the registered model and returns an inference score representing the session’s purchase intent .
If the score exceeds a configured threshold, the system dynamically renders a targeted promotion or discount, enabling in-session personalisation to drive higher conversion rates .
Continuous inference
Session-level caching layer sinks the event data to short-term cloud storage , Snowpipe ingests into Snowflake (staging area)
, enabling near real-time availability of raw session data.
At a defined interval (e.g. every 15 minutes), a micro-batch inference job (Snowflake Task or Python script) is triggered, which aggregates data and calls the deployed model through Snowflake's UDF-style syntax .
Sessions predicted to have high purchase intent but no transaction are flagged and forwarded to a messaging or email dispatch service .
This drives automated cart abandonment recovery, such as sending a personalised email like "Still thinking it over? Here is 15% off your order".
End-of-day / big batch inference
At the end of each day, aggregated session-level data is persisted from the staging layer into a long-term cloud storage zone (datalake) for historical analysis and large-scale processing .
A scheduled batch scoring pipeline is executed within Snowflake, leveraging the previously deployed model via Snowflake’s UDF-style syntax to compute purchase intent scores for all sessions captured that day .
Sessions with high intent scores are exported through reverse ETL pipelines into downstream activation platforms such as Braze, Salesforce, or paid media channels, enabling targeted marketing and personalised outreach at scale .
In parallel, the newly labelled data is incorporated into a model retraining pipeline , which evaluates concept drift, class balance, and performance metrics. If degradation is detected or behavioural patterns shift, a new model version is trained, registered in the Snowflake Model Registry, and seamlessly re-deployed to SPCS, completing the lifecycle.
Final thoughts on real-time purchase prediction with ML
Every single action from the user is a potential conversion, but only if we act fast enough.
In e-commerce, ML is not just about predicting who will purchase. We can capitalise on opportunities while the prediction still matters to the right person, at the right time, and in the right place.
Snowflake’s unified platform and Snowpark Container Services (SPCS) allow us to register, serve, and apply models across the full spectrum of latency:
- Real-time: Influence users while they’re still on the site;
- Micro-batch: Recover lost revenue minutes after a session ends;
- Batch: Fuel your next campaign and retrain your models — at scale.
Inference latency is a business decision. Get it right, and you do not just predict — you convert.
Visit the Infinite Lambda blog for more insights on the latest in data and AI.
Explore cases of applying cutting-edge tech to drive tabgible business outcomes.
Ready to see how data and AI can make a difference in your organisation? Reach out.






